Skip to content

Instantly share code, notes, and snippets.

@deviousasti
Created January 11, 2021 06:45
Show Gist options
  • Save deviousasti/4ddfa530fc4ea13c060c130af737c8cb to your computer and use it in GitHub Desktop.
Save deviousasti/4ddfa530fc4ea13c060c130af737c8cb to your computer and use it in GitHub Desktop.
Kahan Sum Float Error
// @mdl
let rec kahan_sum_aux (xs : float list) (sum : float) (c : float) =
match xs with
| [] -> sum
| x::xs ->
let y = x - c in
let t = sum + y in
let c = (t - sum) - y in
kahan_sum_aux xs t c
let kahan_sum (xs : float list) =
match xs with
| [] -> 0.0
| _ -> kahan_sum_aux xs 0.0 0.0
let () =
let xs = List.replicate 10 0.1 in
let error_sum = List.fold (+) 0.0 xs in
let compensated_sum = kahan_sum xs in
printfn "error_sum = 1.0: %b\ncompensated_sum = 1.0: %b"
(error_sum = 1.0) (compensated_sum = 1.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment