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?