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 float
s?
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?
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).
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.
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.
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.
==
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.
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 >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With