Feature #10298 ยป array.float_sum.patch
array.c | ||
---|---|---|
/*
|
||
* 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<RARRAY_LEN(ary); i++) {
|
||
y = RFLOAT_VALUE(rb_ary_entry(ary,i)) - c;
|
||
t = sum + y;
|
||
c = (t - sum) - y;
|
||
sum = t;
|
||
}
|
||
return DBL2NUM(sum);
|
||
}
|
||
/*
|
||
* call-seq:
|
||
* ary.empty? -> true or false
|
||
*
|
||
* Returns +true+ if +self+ contains no elements.
|
||
... | ... | |
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);
|