52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
# File 'ext/ruby_native_statistics/mathematics.c', line 52
VALUE rb_median(VALUE self)
{
unsigned long array_length;
VALUE result;
Check_Type(self, T_ARRAY);
array_length = RARRAY_LEN(self);
if (array_length <= 0)
{
rb_raise(rb_eRangeError, "array must have at least one element");
}
bool array_even_size = (array_length % 2) == 0;
unsigned long middle = (long)floor(array_length / 2.0);
double *working_array = sorted_ruby_array(self, array_length);
if (!array_even_size)
{
result = DBL2NUM(working_array[middle]);
}
else
{
result = DBL2NUM((working_array[middle - 1] + working_array[middle]) / 2);
}
free(working_array);
return result;
}
|