Float comparison error

Inside a project I have been working in, I detected an anomaly when I make comparisons between two floats numbers. I have reproduced this error in a very basic loop just to show the problem in a simple way :

list_temp = [0.40,0.30,0.20,0.10]
acc = 0 
for number in list_temp
    acc = acc + number 
    println("number = ", number ," ","acc = ", acc)
    if acc == 0.90

I got the following output

number = 0.4 acc = 0.4
number = 0.3 acc = 0.7
number = 0.2 acc = 0.8999999999999999
number = 0.1 acc = 0.9999999999999999

That means, the condition doesn’t not is accomplished even tough it was supposed to be truth. the variable Acc would take the value 0.9 instead of 0.8999999. Because of this, the condition is not satisfied and I got a logical problem in my code. Anyone knows how to deal with it ? I could use something like truncate but I would like to stay with a simple condition and the numbers I will deal with are not big… Thanks in advance.

Use (\approx) for floating point number comparisons.


And if you use \approx, check the documentation for the tolerances you want to use.

1 Like

Note the ability to provide an absolute tolerance atol, a relative tolerance rtol or both. The default relative tolerance is often good but be aware that zero is only approximately equal to itself with the defaults.

1 Like