Hi, quick question about doubles. In Kotlin, `0.1 ...
# getting-started
t
Hi, quick question about doubles. In Kotlin,
0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 < 0.8
evaluates as true, because the left-hand side is actually 0.79r instead of 0.8. What's the best way of dealing with this? I guess I could convert to a string and back, but that feels a little 'hacky'. Is there a better way?
z
If you need accuracy, BigDecimal is the way to go
👍 1
if you're going to stick with floating point, all comparisons should have an error bound
also it's not quite 0.79r or 0.8; neither is exactly representable in floating point
t
👍 thanks both
d
You can also try to use construction like this: if (abs(res-pred) < eps)... where eps is a constant like 10^(-7) etc.
e
Highly recommended read: https://floating-point-gui.de/