python math problem
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Feb 15 23:49:12 EST 2013
Dennis Lee Bieber wrote:
> Classical CompSci teachings when working with floating point numbers
> is to NEVER compare for equality. Instead one should compare against
> some epsilon:
"Don't compare floats for equality" is reasonably good advice.
Adding "never" to that advice, especially when shouting as you do, moves it
into the category "superstition".
Consider:
- Python floating point integers are exact for entire range of -2**53
to 2**53, or about -9 million million to +9 million million; if you
are working with floats that have integral values in this range,
testing for equality is perfectly fine.
- If you work exclusively with fractional powers of two, such as 1/2,
1/4, 1/8, 1/16, etc. floats are typically exact.
- Testing against an epsilon raises as many problems as it solves:
+ What epsilon should I pick? How do I know if my epsilon is too small,
and therefore I'm rejecting values that I should accept, or too large,
and so I'm accepting values I should reject?
+ If my epsilon is too small, calculating "abs(x - y) <= epsilon" is
exactly equivalent to "x == y", only slower.
+ Should I test for absolute error, or relative error?
+ If relative error, how do I deal with values around zero where
division is likely to introduce excessive rounding error?
+ Not to mention the risk of dividing by zero.
- And how do I deal with INFs?
py> x = float('inf')
py> x == x
True
py> abs(x - x) <= 1e-14
False
--
Steven
More information about the Python-list
mailing list