Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Python's == an equivalence relation on the floats?

In native Python, without using NumPy (for which numpy.nan != numpy.nan) there is no NaN, so am I right in thinking that Python's floating point == is reflexive? Then since it is symmetric (a == b implies b == a) and transitive (if a==b and b==c then a==c), can we say that Python's == is an equivalence relation on the floats?

EDIT: OK, so I learned that there is a NaN: float('nan') (thanks @unutbu) which will propagate through various operations, but does any native Python method return it (rather than raising an Exception) without me introducing it by this assignment?

like image 814
xnx Avatar asked Jan 02 '15 14:01

xnx


People also ask

Can we use == to compare two float values in Python?

The common wisdom that floating-point numbers cannot be compared for equality is inaccurate. Floating-point numbers are no different from integers: If you evaluate "a == b", you will get true if they are identical numbers and false otherwise (with the understanding that two NaNs are of course not identical numbers).

Can we compare float in Python?

How To Compare Floats in Python. If abs(a - b) is smaller than some percentage of the larger of a or b , then a is considered sufficiently close to b to be "equal" to b . This percentage is called the relative tolerance. You can specify the relative tolerance with the rel_tol keyword argument of math.

Is Python a float function?

The float() method is a built-in Python function that is used to convert an integer or a string to a floating-point value. The float() method takes in one parameter: the value you want to convert to a float. This parameter is optional and its default value is 0.0.

Can integer be equal to float Python?

In Python, 3 is int and 3.0 is float. Both types are different but both has the same value, that is 3 == 3.0 is true.


1 Answers

== is reflexive for all numbers, zero, -zero, ininity, and -infinity, but not for nan.

You can get inf, -inf, and nan in native Python just by arithmetic operations on literals, like below.

These behave correctly, as in IEEE 754 and without math domain exception:

>>> 1e1000 == 1e1000 True >>> 1e1000/1e1000 == 1e1000/1e1000 False 

1e1000 is a very big number, so float and double represent it as an infinity.

  • infinity is equal to infinity
  • infinity divided by infinity is not a number
  • not a number != not a number

Floating-point arithmetic in Python also works OK for infinity minus infinity etc.:

>>> x = 1e1000 >>> x inf >>> x+x inf >>> x-x nan >>> x*2 inf >>> x == x True >>> x-x == x-x False >>>  

And for the zero and minus zero case:

>>> inf = float("inf") >>> 1/inf 0.0 >>> -1/inf -0.0 >>> -1/inf == 1/inf True >>>  
like image 169
user2622016 Avatar answered Sep 19 '22 16:09

user2622016