Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Imprecise summation for Float32 #23

Open
hsgg opened this issue Aug 8, 2022 · 3 comments
Open

Imprecise summation for Float32 #23

hsgg opened this issue Aug 8, 2022 · 3 comments

Comments

@hsgg
Copy link

hsgg commented Aug 8, 2022

This package can have less precision than the standard sum() on julia-1.7.3. For example:

julia> using KahanSummation

julia> x = rand(Float32, 10_000_000) .+ 1f5;

julia> sum_kbn(x)
9.9479867f11

julia> sum(x)
1.00000504f12

Is this expected?

@ararslan
Copy link
Member

ararslan commented Aug 8, 2022

How do you mean less precise?

If you mean f11 vs. f12, note that 9.9479867f11 === 0.99479867f12. (Typically in scientific notation you change the exponent rather than have a leading zero.)

@hsgg
Copy link
Author

hsgg commented Aug 8, 2022

How do you mean less precise?

Sorry, what I mean is that the correct result is >1f12, and sum() gets it pretty well.

Actually, a better test case is without randomness. For example,

julia> x = fill(1f5, 10_000_000);

julia> sum_kbn(x)
9.9477704f11

julia> sum(x)
1.0f12

julia> 10_000_000 * 1f5
1.0f12

The error for sum_kbn() is ~0.5%.

@ararslan
Copy link
Member

ararslan commented Aug 8, 2022

Interestingly, the original Kahan-Babuška algorithm gets it right but Neumaier's extension (i.e. sum_kbn) gets it wrong: the running compensation term ends up overcompensating.

julia> function sum_kb(x)
           s = c = zero(eltype(x))
           for xi in x
               y = xi - c
               t = s + y
               c = (t - s) - y
               s = t
           end
           return s
       end
sum_kb (generic function with 1 method)

julia> sum_kb(x)
1.0f12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants