Math.sqrt for negative numbers

Hello,

I’m currently being struggled working with complex numbers in Java, while developing a plugin.
After my research, I found out that Java doesn’t offer a ‘native’ solution for complex numbers, and I rather do some workaround.

I’m familiar with Jython and currently discovering it, but before I dive in, does anyone knows how to handle complex numbers in Java (maybe using ImageJ or other handful libraries)?

Thanks!

You could try apache commons math:
https://commons.apache.org/proper/commons-math/javadocs/api-3.6/org/apache/commons/math3/complex/Complex.html

1 Like

Hello Yarin -

Not a direct answer to your java question …

Jython (a version of python 2), which you can use as a scripting
language in Fiji / ImageJ, comfortably supports complex numbers
and complex functions.

Here is an example script:

x = -4
print  type (x)
z = complex (x)
print  type (z)
import cmath
r1 = cmath.sqrt (x)
print  r1, type (r1)
r2 = cmath.sqrt (z)
print  r2, type (r2)
rr2 = cmath.sqrt (r2)
print  rr2

And here is its output:

<type 'int'>
<type 'complex'>
2j <type 'complex'>
2j <type 'complex'>
(1+1j)

If you’re building your plugin in java (and it’s not really simple
enough to do it all in jython), then it probably isn’t worth the bother
to “outsource” the complex square root from java to jython. You’re
probably better off using an “external” library, such as the apache
commons library Chris mentioned, or, if it’s just a few simple
manipulations you need to do, just roll your own.

Thanks, mm

1 Like

Looks great, thanks @cwood1967
I’m checking it