Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does “np.inf // 2” result in NaN and not infinity?

I’m slightly disappointed that np.inf // 2 evaluates to np.nan and not to np.inf, as is the case for normal division.

Is there a reason I’m missing why nan is a better choice than inf?

like image 434
Aguy Avatar asked Aug 11 '20 17:08

Aguy


People also ask

Can we not say that INF is not equivalent to Nan?

-inf is therefore smaller than any other value. nan stands for Not A Number, and this is not equal to 0 . Although positive and negative infinity can be said to be symmetric about 0 , the same can be said for any value n , meaning that the result of adding the two yields nan .

What is the value of NP INF?

np. inf is for positive infinity, and -np. inf is for negative infinity.


Video Answer


2 Answers

I'm going to be the person who just points at the C level implementation without any attempt to explain intent or justification:

*mod = fmod(vx, wx); div = (vx - *mod) / wx; 

It looks like in order to calculate divmod for floats (which is called when you just do floor division) it first calculates the modulus and float('inf') %2 only makes sense to be NaN, so when it calculates vx - mod it ends up with NaN so everything propagates nan the rest of the way.

So in short, since the implementation of floor division uses modulus in the calculation and that is NaN, the result for floor division also ends up NaN

like image 60
Tadhg McDonald-Jensen Avatar answered Sep 29 '22 04:09

Tadhg McDonald-Jensen


Floor division is defined in relation to modulo, both forming one part of the divmod operation.

Binary arithmetic operations

The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y). Floor division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x//y, x%y).

This equivalence cannot hold for x = inf — the remainder inf % y is undefined — making inf // y ambiguous. This means nan is at least as good a result as inf. For simplicity, CPython actually only implements divmod and derives both // and % by dropping a part of the result — this means // inherits nan from divmod.

like image 29
MisterMiyagi Avatar answered Sep 29 '22 05:09

MisterMiyagi