Why is there a difference when you Sum over an Array versus a Generator?

Vector summation:
‘’’ sum([1/n^2 for n = 1:100000])’’’
returns: 1.644924066898228

Generator summation:
‘’‘sum((1/n^2 for n = 1:100000))’’’
returns: 1.6449240668982423

Why is there a difference in these results, and which summation method is the most accurate?

https://0.30000000000000004.com/. The list version uses pairwise summation which means on average it will be slightly more accurate.

3 Likes

Thank you. For clarification, is the list version the vector summation method (i.e. enclosed in with brackets)?

Yeah.

For an even more accurate result, sum the terms in order of increasing absolute value:

sum((1/n^2 for n = 100000:-1:1))   # returns 1.6449240668982263

or use BigFloat:

sum((1/big(n)^2 for n = 1:100000)) # returns 1.64492406689822626980574850331269185564752...
2 Likes

if you want it accurate AND fast you may have a look at GitHub - JuliaMath/AccurateArithmetic.jl: Calculate with error-free, faithful, and compensated transforms and extended significands.

3 Likes