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)