Yeah, I did the same thing with tests. Wrote about ten of them and rigged the suite to scream “YOU FAIL” at me without even printing the line number. Couldn’t believe it when they all passed on the first try :-)
Did you consider that comparing floating point numbers with ‘==’ doesn’t make much sense?
No. What do you propose? Use some sort of “comparison tolerance”?
No. What do you propose? Use some sort of “comparison tolerance”?
That depends on the concrete numerical application. Typically you’d define some threshold for the difference, and use “abs(x-y)<threshold” instead of “x==y”, or some variation on that theme. But exact bit-by-bit equality comparisons of floats practically never make sense, since even very simple arithmetic will likely produce rounding errors, so seeing ‘==’ between floats almost always means that something nonsensical is going on. (See e.g. here for some elaboration.)
These issues with limited floating point precision make numerical programming extremely tricky. You have a whole alternative set of rules for arithmetic, very different from those you normally follow on paper.
I think I’d have a different implementation for floats that would return the nearest two it’s between, and punt the tolerance decision up a level to the calling code.
Yeah, I did the same thing with tests. Wrote about ten of them and rigged the suite to scream “YOU FAIL” at me without even printing the line number. Couldn’t believe it when they all passed on the first try :-)
No. What do you propose? Use some sort of “comparison tolerance”?
In this context, I think the answer is don’t write it for floats!
cousin_it:
That depends on the concrete numerical application. Typically you’d define some threshold for the difference, and use “abs(x-y)<threshold” instead of “x==y”, or some variation on that theme. But exact bit-by-bit equality comparisons of floats practically never make sense, since even very simple arithmetic will likely produce rounding errors, so seeing ‘==’ between floats almost always means that something nonsensical is going on. (See e.g. here for some elaboration.)
These issues with limited floating point precision make numerical programming extremely tricky. You have a whole alternative set of rules for arithmetic, very different from those you normally follow on paper.
I think I’d have a different implementation for floats that would return the nearest two it’s between, and punt the tolerance decision up a level to the calling code.