0

I have written two ways of calculating the harmonic series - one with a while loop and one with a for loop. The methods calculate and add the terms in opposite orders:

H(x) = 1/x + ... + 1/2 + 1

acc1 = 0

i = x
while i > 0:
    acc1 += 1/i
    i -= 1

print(acc1)

H(x) = 1 + 1/2 + ... + 1/x

acc2 = 0

for k in range(x):
    acc2 += 1/(k+1)

print(acc2)

The two methods find the sum of the same numbers. It is just the order that is different. But for x >= 26, I get a very small difference between the outputs (approx. 4e-16 for x = 26). I understand that floating point addition often causes small inaccuracies in programming due to recurring decimals in base 2 - but for adding the same numbers, why are the two outputs different?

Charley
  • 35
  • 4
  • 2
    You just answered yourself. Because of floating point math, addition is NOT commutative using floats. The error is well within range of float approximation errors. – Marco Bonelli Oct 28 '19 at 09:31
  • Relevant: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Emily Oct 28 '19 at 09:35

0 Answers0