result of isequal(0.6, 0.5 + 0.1) differs from isequal(0.6, 0.4 + 0.2) in julia

Viewed 59

I'm learning Julia currently and have encountered a strange result (which I don't think to be Julia's specific behavior!), and I'm eager to find out why. In Julia, one can check the equality between two values (like Integer, Float, etc.) using == or isequal(). For example, you can check the equality between 4 and the expression 2+2 like this:

julia> isequal(4, 2+2)
true

But when I tried these two following statements, I got an unexpected result:

julia> isequal(0.6, 0.5 + 0.1)
true

julia> isequal(0.6, 0.4 + 0.2)
false

I'm confused why this differs. Any help would be appreciated.

Also is there function in Julia that can perform an inexact equality comparison?

1 Answers

The numbers such as 0.1 or 0.2 are not rational numbers in the binary system so you end up having rounding errors. This behaviour is according to the IEEE floating point standard, and is present in all mainstream programming languages (eg. the same behavior can be observed in Python, C++, C#, Java or even Microsoft Excel).

In Julia there is the isapprox function having a corresponding operator ā‰ˆ.


julia> 0.2 + 0.4 == 0.1 + 0.5
false

julia> 0.2 + 0.4 ā‰ˆ 0.1 + 0.5
true

Another option would be to bring your arithmetic to rational numbers:


julia> 2//10 + 4//10 == 1//10 + 1//2
true

Note that converting between floats and rational numbers is not so easy:

julia> Rational(0.2)
3602879701896397//18014398509481984

Instead use rationalize function that has optional tolerance parameter:

julia> rationalize(0.2)
1//5
Related