The average number of complex numbers with infinity

numpy doesn't seem to be a good friend of complex infinities

So far we can evaluate:

In[2]: import numpy as np

In[3]: np.mean([1, 2, np.inf])
Out[3]: inf

The following result is more cumbersome:

In[4]: np.mean([1 + 0j, 2 + 0j, np.inf + 0j])
Out[4]: (inf+nan*j)
...\_methods.py:80: RuntimeWarning: invalid value encountered in cdouble_scalars
  ret = ret.dtype.type(ret / rcount)

I'm not sure that the imaginary part makes sense to me. But comment if I am wrong.

Any understanding of interactions with complex infinities in numpy?

+6
source share
3 answers

Decision

To calculate the average, we divide the sum by a real number. This separation causes problems due to type advancement (see below). To avoid type advancement, we can manually perform this separation separately for the real and imaginary parts of the sum:

n = 3
s = np.sum([1 + 0j, 2 + 0j, np.inf + 0j])
mean = np.real(s) / n + 1j * np.imag(s) / n
print(mean)  # (inf+0j)

Justification

numpy, , . , ((1 + 0j) + (2 + 0j) + (np.inf + 0j)) / (3+0j) (inf+nanj).

. , . , :

 a + bj
--------
 c + dj

divisoin , d=0. , , j . :

 a + bj     (a + bj) * (c - dj)     ac + bd + bcj - adj
-------- = --------------------- = ---------------------
 c + dj     (c + dj) * (c - dj)        c**2 + d**2

, a=inf d=0 a * d * j = inf * 0 * j = nan * j.

+2

np.inf , np.mean , np.max(). mean(), , , undefined, non*j .

, . isfinite() :

In [16]: arr = np.array([1 + 0j, 2 + 0j, np.inf + 0j])

In [17]: arr[np.isfinite(arr)]
Out[17]: array([ 1.+0.j,  2.+0.j])

In [18]: np.mean(arr[np.isfinite(arr)])
Out[18]: (1.5+0j)
+4

- .

, (inf + 0j) / 2, () 2 + 0j.

(0 * 2 - inf * 0) / 4. inf * 0 , NaN. NaN.

. numpy , . "", . . inf , , () .

:

IEEE "" , , 1 / 0. , . inf NaN " " , . , .

, . 1 / 0 . (). , ( ) . , .

Tl; dr: // , ( ).

+1

Source: https://habr.com/ru/post/1016782/


All Articles