Skip to content

Instantly share code, notes, and snippets.

@kajic
Created April 25, 2013 13:32
Show Gist options
  • Save kajic/5459711 to your computer and use it in GitHub Desktop.
Save kajic/5459711 to your computer and use it in GitHub Desktop.
Kahan sum
# Reduces numerical error when adding a sequence of floats.
# http://en.wikipedia.org/wiki/Kahan_summation_algorithm
#
# Examples:
#
# Sums all given arguments:
# KahanSum.new([3.14159265358979323846 , 2.71828182845904523536], 1.41421356237309504880)
# => #<KahanSum:0x007fd218984120 @sum=7.274088044421934, @c=2.220446049250313e-16>
#
# Incremental summation:
# sum = KahanSum.new
# sum+3.14159265358979323846
# sum+2.71828182845904523536
# sum+1.41421356237309504880
# => 7.274088044421934
class KahanSum
def initialize(*args)
@sum = 0.0
@c = 0.0
args.each { |arg| Array(arg).each {|n| self+n } }
end
def +(n)
y = n - @c
t = @sum + y
@c = (t - @sum) - y
@sum = t
end
def to_f
@sum
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment