From: Nobuyoshi Nakada Date: 2009-11-03T18:57:30+09:00 Subject: [ruby-core:26491] Re: Add Standard Deviation Function to Math Module Hi, At Tue, 3 Nov 2009 11:05:36 +0900, Daniel Cohen wrote in [ruby-core:26490]: > I was thinking that a Statistics module would be a good addition to Ruby. If > you decide that it would be worth creating one, I would be happy to > contribute. statistics/extconf.rb and statistics/statistics.c. require 'mkmf' create_makefile('statistics') #include #include struct stat_stdev_args { double sum, sum2; long num; }; static VALUE stdev_i(VALUE elem, VALUE arg, int argc, VALUE *argv) { struct stat_stdev_args *a = (void *)arg; double x = NUM2DBL(elem); a->sum += x; a->sum2 += x*x; a->num++; return Qnil; } /* * call-seq: * Statistics.stdev(enum) => double * * Computes the standard deviation of the elements in an enum * If they are all numbers. */ static VALUE stat_stddev(VALUE obj, VALUE list) { long i; struct stat_stdev_args args; double mean, stddev; args.sum = args.sum2 = 0.0; args.num = 0; rb_iterate(rb_each, list, stdev_i, (VALUE)&args); mean = args.sum / args.num; stddev = sqrt(args.sum2 / args.num - mean*mean); return DBL2NUM(stddev); } void Init_statistics(void) { VALUE mStatistics = rb_define_module("Statistics"); rb_define_singleton_method(mStatistics, "stddev", stat_stddev, 1); } -- Nobu Nakada