Project

General

Profile

Feature #2322 ยป add_stdev.diff

Patch to add standard deviation feature - danielc192 (Daniel Cohen), 11/02/2009 05:29 AM

View differences:

math.c 2009-11-01 15:23:53.000000000 -0500
61 61
    }
62 62
}
63 63

  
64
/*
65
 *  call-seq:
66
 *     Math.stdev(array)   =>   double
67
 *
68
 *  Computes the standard deviation of the elements in an <i>array</i>
69
 *  If they are all numbers.
70
 *
71
 *
72
 */
73
 
74
static VALUE
75
math_stdev(VALUE obj, VALUE ary)
76
{		
77
	long i;
78
	double sum = 0.0;
79
	double mean = 0.0;
80
	double numer = 0.0;
81
	
82
	
83
	for (i=0; i<RARRAY_LEN(ary); i++) {
84
	if( TYPE(RARRAY_PTR(ary)[i]) == T_STRING) {
85
		rb_raise(rb_eTypeError, "Element is not a number!");
86
	} else {
87
		sum = sum +  NUM2DBL(RARRAY_PTR(ary)[i]);
88
	}
89
	}
90
	mean = sum / RARRAY_LEN(ary);
91
	
92
	for (i=0; i<RARRAY_LEN(ary); i++) {
93
	if( TYPE(RARRAY_PTR(ary)[i]) == T_STRING) {
94
		rb_raise(rb_eTypeError, "Element is not a number!");
95
	} else {
96
		numer = numer + pow((NUM2DBL(RARRAY_PTR(ary)[i]) - mean), 2);
97
	}
98
	}
99
	
100
	return DBL2NUM(sqrt(numer / RARRAY_LEN(ary)));
101
}
102

  
64 103

  
65 104
/*
66 105
 *  call-seq: