Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do NumPy operations with complex infinities lead to funny results?

Tags:

python

numpy

I've noticed funny results with complex infinities.

In [1]: import numpy as np

In [2]: np.isinf(1j * np.inf)
Out[2]: True

In [3]: np.isinf(1 * 1j * np.inf)
Out[3]: True

In [4]: np.isinf(1j * np.inf * 1)
Out[4]: False

This is nan related. But the end result is bizarre.

Is it a numpy bug? Anything I should do differently?

like image 310
Aguy Avatar asked Aug 04 '16 21:08

Aguy


1 Answers

It's not a NumPy bug. numpy.inf is a regular Python float, and the strange results come from the regular Python complex multiplication algorithm, which is this:

Py_complex
_Py_c_prod(Py_complex a, Py_complex b)
{
    Py_complex r;
    r.real = a.real*b.real - a.imag*b.imag;
    r.imag = a.real*b.imag + a.imag*b.real;
    return r;
}

When the inputs have infinite real or imaginary parts, complex multiplication tends to cause inf-inf subtraction and 0*inf multiplication, leading to nan components in the result. We can see that 1j * numpy.inf has one nan component and one inf component:

In [5]: 1j * numpy.inf
Out[5]: (nan+infj)

and multiplying the result by 1 produces two nan components:

In [4]: 1j * numpy.inf * 1
Out[4]: (nan+nanj)
like image 72
user2357112 supports Monica Avatar answered Nov 14 '22 23:11

user2357112 supports Monica