Can someone try adding 370.1 + 0.1 and see if you ...
# announcements
b
Can someone try adding 370.1 + 0.1 and see if you get 370.2? If it is, try this
Copy code
val x = 370.1
x + 0.1
I'm getting 370.20000000000005 on a few different Kotlin versions
1
a
for floating point numbers, it's not possible to represent 0.1 as an exact number
for example in decimal numbers, it's impossible to represent exactly 1/3, it would be 0.33333..., the same way in binary it's impossible to exactly represent 0.1
2
you can format it to a certain number of decimal places (e.g. 5 or 10) when you are displaying it, that way the user will see a nice round number
e
if you're working with floating point and haven't read through https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html … well you need to read it
a
if you want to compare 2 floating point numbers e.g. to see if they are "equal", you can check if their difference is less than some threshold. if (abs(a - b) < 0.0000001) { ... }
e
the appropriate delta value will differ depending on the magnitude, the calculations, the JVM, the hardware…
👍 1
a
and if you really need to work with exact numbers, you'll need to avoid floating points, e.g. use BigDecimal
e
but at the very least there's no point in checking for any delta smaller than ulp of the results
note that if you want precisely reproducible results between machines/jvms, you need @Strictfp (which will run slower on some hardware)
a
good point, although interesting that this distinction for strictfp is going away in JDK 17: https://openjdk.java.net/jeps/306
b
I'm just trying to release a hotfix for our company so I don't need large floats. I might just have to work around it by working with strings instead of a double or float. The decimal will always be small for us. In fact string night have been better in the first place because 370.9 + 0.1 would be 371.0 instead of 370.10
e
consider using fixed point instead
1
yeah, a big motivation for strictfp was the x86 FPU with it's funky 80-bit floats which nobody cares about anymore now that we're all on 64-bit with SSE available
a
for fixed point, you can e.g. use Long counting the number of pennies instead of Double counting dollars
1
b
That makes sense to me. This is some interesting stuff that I vaguely remember in college so it's kinda cool to see it in action. Thanks for the info!
👍 1
e
This site has good and approachable explanation: https://floating-point-gui.de/