0

I've started using the Julia language, but I'm surprised to get seemingly incorrect results with even basic operations:

julia> 0.05*0.05
0.0025000000000000005

and

julia> 1.0-0.85-0.1
0.05000000000000002

How can this be? And what can I do to obtain exact results?

carlos1985
  • 318
  • 1
  • 9

1 Answers1

10

I'm surprised to get seemingly incorrect results with even basic operations [...] How can this be?

Binary IEEE-754 floating-point numbers (which Julia uses) cannot represent numbers such as 0.05, 0.85, and 0.1 exactly.

For instance, when you write 0.05 in Julia, the number that the machine manipulates is a number very close to the actual number 0.05, but not exactly 0.05. Therefore, you cannot expect Julia expressions such as 0.05*0.05 to evaluate to exactly 0.0025.

More counterintuitive examples? Try

julia> 1-0.2-0.2-0.2-0.2-0.2
5.551115123125783e-17

julia> 0.6/0.2 == 3
false

If you're interested (and even if you're not!), I strongly recommend David Goldberg's What every computer scientist should know about floating-point arithmetic. You may also be interested in this related answer of mine on the TeX sister site.


And what can I do to obtain exact results?

Are you only manipulating rational numbers? If so, know that Julia provides a rational types, i.e. types that allow you to represent fractions exactly.

The rational type used by default, Rational{Int64}, is capable of representing any rational number whose numerator and denominator fall in the range of 64-bit integers. You can use this rational type to carry out exact operations (barring integer overflow) on rational numbers:

julia> 1//20 * 1//20
1//400

julia> 1 - 17//20 - 1//10
1//20

Moreover, if you want arbitrary-precision rational numbers, you can use the Rational{BigInt} type (see Mr Alpha's comment)

Community
  • 1
  • 1
jub0bs
  • 60,866
  • 25
  • 183
  • 186