(Mar-24-2022, 06:09 AM)deanhystad Wrote: There is so much wrong that this really can't be called Python code.
Ouch!!! That's cruel and unfair. It
really can be called Python code. Not the best Python code, and it has at least one syntax error, but it is Python code.
deanhystad Wrote:You should not use == when comparing float numbers. Your equation may return a value really close to zero, but it is unlikely any combination of arguments will produce a result that is exactly zero. That is just the nature of floating point math on computers; ridiculous resolution, but almost never results that are exactly right.
That is pure superstition, and bad advice. Please don't say that, it really is terrible, terrible advice.
Python uses IEEE-754 floats, and equality in IEEE-754 is perfectly well defined. Two floats will compare equal if, and only if, they actually are equal. And there are vast numbers of expressions that will result in exactly zero, starting with the most obvious cases
x*0.0
and
x - x
, and going to more complex expressions:
# All of these will return 0.0
math.sin(0.0)
math.exp(-1000)
math.acos(-1.0) - math.pi
(2/3)**2 - 4/9
0.5**1075
(1/8 + 1/64)**2 - 81/8**4
and many, many more. They aren't even hard to find.
Although it is true that
arbitrary float expressions may not give exactly zero, that is very different from "you should not...".
Unlike floating point arithmetic pre-IEEE-754, it is
never the case that
if x != 0:
y = 1/x
can fail with a ZeroDivisionError. It just cannot happen, which was not the case back in the dark ages prior to IEEE-754.
Using
math.isclose()
is the wrong solution here. And why choose 1e-9 for the tolerance? Where does that magic value come from? Floats have about 16-17 significant figures of precision, so you are accepting
billions of legitimately non-zero floats as "close enough" to zero.
It is especially, doubly wrong when the OP's intention is to record the combination of values which actually do give a result of zero.
Please read
Bruce Dawson, he's writing from a C++ perspective but if you remember that Python floats are C/C++ doubles you can't go wrong.
"don’t blindly trust floating-point math, but don’t assume that it introduces errors at random." -- Bruce Dawson.