2

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?

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
Shayan
  • 5,165
  • 4
  • 16
  • 45
  • I think, in the context of Julia, this question has a more specific answer than the one linked, since in Julia the `isapprox` function written as `≈` operator is supported and with this function both tests would return `true`. – Bogumił Kamiński Jul 07 '22 at 20:12
  • @BogumiłKamiński So what should I do to reopen this question? – Shayan Jul 07 '22 at 20:27
  • The question is is if my comment about `isapprox` is enough for you. If yes - then probably no need to reopen. If you want more explanation I can reopen. – Bogumił Kamiński Jul 07 '22 at 20:28
  • @BogumiłKamiński yes, I'm eager to know more please. – Shayan Jul 07 '22 at 20:30

1 Answers1

4

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
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • 2
    Maybe the answer should mention that this behaviour is according to the ieee floating point standard, and is common to all mainstream programming languages. Right now, it's possible to interpret this as something weird that Julia does, and needs to be worked around. – DNF Jul 08 '22 at 07:45
  • 1
    @DNF done - you are right to be more detailed :D – Przemyslaw Szufel Jul 08 '22 at 11:53