3 ms·
This is a fairly obvious one? Although I've mainly encountered the effect with long to double conversion. On the other hand, floating point is the gift that n
by derriz 1y ago
This is a fairly obvious one? Although I've mainly encountered the effect with long to double conversion.
On the other hand, floating point is the gift that never stops giving.
A recent wtf I encountered was partly caused by the silent/automatic conversion/casting from a float to double. Nearly all C-style languages do this even though it's unsafe in its own way. Kinda obvious to me now and when I state it like this (using C-style syntax), it looks trivial but: (double) 0.3f is not equal to 0.3d
The wtfness of it was mostly caused by other factors (involving overloaded method/functions and parsing user input) but I realized that I had never really thought about this case before - probably because floats are less common than doubles in general - and without thinking about it, sort of assumed it should be similar to int to long conversion for example (which is safe).
- secondcoming 1y ago-Wfloat-conversion will warn about this. Been bitten by it too.
- taneq 1y agoThis sort of thing is why you never compare floating point numbers for equality. Always compare using epsilons appropriately chosen for the circumstances. Floats are Sneaky and Not to be Trusted. :D
- sjrd 1y agoAlways... except when you're actually writing floating point operations. If I'm implementing `sqrt`, I'd better make sure the result is exactly the expected one. Epsilon is 0 in all my unit tests. ;)
- taneq 1y agoThis is true! As an implementor of floating point operations, you want to be exactly correct for all values (glares at Intel :P ) However, as a consumer of said floating point operations, I'm still gonna treat everything as Sneaky And Not To Be Trusted. :P Especially in C++ where this attribute is largely supplied by the compiler being /r/iamverysmart about this sort of thing.
- sjrd 1y agoFloat to double conversion is safe. The thing that's not safe in your example is to write `0.3f` (or `0.3d`) in the first place. The conversions from decimal to float or double is unsafe (inexact) and gives different results from floats than for doubles. But the conversion of float to double, in itself, is always exact.
- derriz 1y agoI do not consider it safe. The float representation of 0.3 (e.g.) does not, when cast to double, represent 0.3 - in contrast the i32 representation of any number when cast to i64 represents the same number.