Question

At some point in my python script, I require to make the calculation: 1*(-inf + 6.28318530718j). I understand why this will return -inf + nan*j since the imaginary component of 1 is obviously 0, but I would like the multiplication to have the return value of -inf + 6.28318530718j as would be expected. I also want whatever solution to be robust to any of these kinds of multiplications. Any ideas?

Edit:

A Complex multiplication like x*y where x = (a+ib) and y = (c+id) I assume is handled like (x.real*y.real-x.imag*y.imag)+1j*(x.real*y.imag+x.imag*y.real) in python as this is what the multiplication comes down to mathematically. Now if say x=1.0 and y=-inf+1.0j then the result will contain nan's as inf*0 will be undefined. I want a way for python to interpret * so that the return value to this example will be -inf+1.0j. It seems unnecessary to have to define my own multiplication operator (via say a function cmultiply(x,y)) such that I get the desired result.

Was it helpful?

Solution 2

If I use np.log(0), I get a warning like:

>>> 1*(np.log(0) + 6.28318530718j)
__main__:1: RuntimeWarning: divide by zero encountered in log
__main__:1: RuntimeWarning: invalid value encountered in cdouble_scalars
(-inf+nan*j)

I would advise against trying to "work with" inf and nan. You can change the behaviour of numpy using numpy.seterr:

>>> np.seterr(divide='raise')
{'over': 'warn', 'divide': 'raise', 'invalid': 'warn', 'under': 'ignore'}
>>> 1*(np.log(0) + 6.28318530718j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FloatingPointError: divide by zero encountered in log

Now you can catch the FloatingPointError exception and deal with it in some useful way.

Note that the nan part of original answer is actually a side effect of the inf. If you do:

>>> 1*(2 + 6.28318530718j)
(2+6.28318530718j)

If one part of the multiplication has no complex component, it doesn't create a nan in the other side.

OTHER TIPS

The short answer is that the C99 standard (Annex G) on complex number arithmetic recognizes only a single complex infinity (think: Riemann sphere). (inf, nan) is one representation for it, and (-inf, 6j) is another, equivalent representation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top