Hey there, why does `0.42.rem(0.14)` return `0.13...
# mathematics
n
Hey there, why does
0.42.rem(0.14)
return
0.13999999999999996
and how can I fix it?
Intellij even suggests me to change the expression
0.42.rem(0.14) == 0.0
to
false
but
0.28.rem(0.14) == 0.0
is
true
a
floating point arithmetics 😔
a
It is called https://en.wikipedia.org/wiki/IEEE_754. The only way to avoid it is to use BigDecimal.
n
BigDecimal(0.42).rem(BigDecimal(0.14))
doesn't solve the problem
a
Because it uses limited MathContext by default. It could be done, but I need to remember how. In general, you can't check equality of floating point numbers, the correct way is to do it like this:
require( abs(0.42.rem(0.14)) < 1e-4))
You can add an extension to do that
https://pl.kotl.in/qOAIWX6XZ here is how it looks with BigDecimal. But it is not recommended.
n
both solutions work. Thanks!
I still don't understand why
0.28.rem(0.14) == 0.0
is true though
and also
0.56.rem(0.14) == 0.0
a
I think it is the problem of the latest bit flip. The problem is that due to floating precision 0.42 is slightly smaller than 3*0.14 so you get almost 0.14 as a reminder.
println(0.42 >= 3*0.14)
it is false
n
thanks @altavir
a
BigDecimal works but you need to use the string or .valueOf constructor to avoid any floating point issues
Copy code
BigDecimal.valueOf(0.42).rem(BigDecimal.valueOf(0.14))