Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Don't compare floats vs floats with an exact comparison.

I've recently seen a version of this error where someone's code was calculating how many bits a field needed to be to hold the maximum value they cared about.

    bits = floor(log(max_value) / log(2)) + 1
This is playing with fire: it trusts that dividing one approximated irrational value divided by another approximated irrational value will yield a ratio equal or greater than the desired value when max_value is a power of two. Depending exactly how those approximations are rounded, log(8)/log(2) might return 2.999999999999 (bug!), or it might be 3.000000000 (their assumption), or epsilon more than 3.0 (not a bug).



This is one reason why even code that looks "obviously correct" probably deserves a test. If your assumption is true on one platform but not another, the test's failure on it will alert you of the fact.


That's especially a shame, because log2 of a floating point value is particularly easy to calculate, and most math libraries will internally calculate logs of other based (like ln) by finding the equivalent log2 first and then converting it.

And if you want just the floor of the base-2 log, you almost don't even need to calculate it at all; it's right there in the exponent bits.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: