Julia: Floats sum is wrong?

Viewed 95

How can I make sure that by adding 0.2 at every iteration I get the correct result?

some = 0.0
for i in 1:10
    some += 0.2
    println(some)
end

the code above gives me

0.2
0.4
0.6000000000000001
0.8
1.0
1.2
1.4
1.5999999999999999
1.7999999999999998
1.9999999999999998
2 Answers

Floats are only approximatively correct and if adding up to infinity the error will become infinite, but you can still calculate with it pretty precisely. If you need to evaluate the result and look if it is correct you can use isapprox(a,b) or a ≈ b.

I.e.

some = 0.
for i in 1:1000000
    some += 0.2
end
isapprox(some, 1000000 * 0.2)
# true

Otherwise, you can add integer numbers in the for loop and then divide by 10.

some = 0.
for i in 1:10
    some += 2.
    println(some/10.)
end
#0.2
#0.4
#0.6
#0.8
#1.0
#1.2
#1.4
#1.6
#1.8
#2.0

More info about counting with floats: https://en.wikipedia.org/wiki/Floating-point_arithmetic

You can iterate over a range since they use some clever tricks to return more "natural" values:

julia> collect(0:0.2:2)
11-element Vector{Float64}:
 0.0
 0.2
 0.4
 0.6
 0.8
 1.0
 1.2
 1.4
 1.6
 1.8
 2.0

julia> collect(range(0.0, step=0.2, length=11))
11-element Vector{Float64}:
 0.0
 0.2
 0.4
 0.6
 0.8
 1.0
 1.2
 1.4
 1.6
 1.8
 2.0
Related