Different results for loops with decrement and increment

787 views Asked by At

I have come to realize that I don't get the same result between iterations with increment and decrement. I get a slight difference when this math expression n + (1/(i^4)) iterates and adds a new value over itself 75+ times, being i the number of the iteration. Under 75 iterations the result for each loop remains the same. Any ideas of why this is happening? This is the code I am running:

y=0
for i in 1:75
   y = y + (1/(i^4)) 
end
print("final y value: ",y,"\n")

x=0

for i in 75:-1:1
    x = x + (1/(i^4))
end

print("final x value: ",x,"\n")

And I got this for x and y:

final y value: 1.0823224592496965
final x value: 1.0823224592496967

But if i change the loop limits to 74 or less (74 in the following example), I get the same result for both loop:

final y value: 1.0823224276447583
final x value: 1.0823224276447583
1

There are 1 answers

1
Michael K. Borregaard On BEST ANSWER

That is because of floating point rounding errors that take place during the addition, because of the precision of a Float64. You can use arbitrary precision floats (i.e. BigFloats) to overcome this issue if the rounding errors are important.

y = BigFloat(0)
#0.000000000000000000000000000000000000000000000000000000000000000000000000000000

for i in 1:75
   y += 1/(i^4)
end

x = BigFloat(0)
for i in 75:-1:1
   x += 1/(i^4)
end

print("final x value: ",x,"\n")
#final x value: 1.082322459249696627186876349853547531892905553263517504092305898666381835937500

print("final y value: ",y,"\n")
#final y value: 1.082322459249696627186876349853547531892905553263517504092305898666381835937500

Note also that in your original code you define x and y as Int's and then proceed to add Float64's to them - this will seriously slow down your code ( https://docs.julialang.org/en/latest/manual/performance-tips/#Avoid-changing-the-type-of-a-variable-1 )

Also check out https://github.com/JuliaArbTypes/ArbFloats.jl