diff --git a/array.c b/array.c index 9884092..dfc608f 100644 --- a/array.c +++ b/array.c @@ -1892,6 +1892,33 @@ rb_ary_length(VALUE ary) /* * call-seq: + * ary.float_sum -> float + * + * Returns accurate sum of float elements in +self+. + * Uses the Kahan summation algorithm. + * + * [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1].float_sum #=> 1.0 + * [].float_sum #=> 0.0 + */ + +static VALUE +rb_ary_float_sum(VALUE ary) +{ + long i; + double y,t,c,sum; + sum = 0.0; + c = 0.0; + for (i=0; i true or false * * Returns +true+ if +self+ contains no elements. @@ -5719,6 +5746,7 @@ Init_Array(void) rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0); rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0); rb_define_method(rb_cArray, "length", rb_ary_length, 0); + rb_define_method(rb_cArray, "float_sum", rb_ary_float_sum, 0); rb_define_alias(rb_cArray, "size", "length"); rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0); rb_define_method(rb_cArray, "find_index", rb_ary_index, -1);