Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Floats sum is wrong?

Tags:

julia

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
like image 910
Euler_Salter Avatar asked Jan 25 '23 13:01

Euler_Salter


1 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

like image 108
Oskar Avatar answered Feb 03 '23 23:02

Oskar