Module: Mathematics

Included in:
Array
Defined in:
ext/ruby_native_statistics/ruby_native_statistics.c

Instance Method Summary collapse

Instance Method Details

#meanObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'ext/ruby_native_statistics/mathematics.c', line 36

VALUE rb_mean(VALUE self)
{
  unsigned int array_length;

  Check_Type(self, T_ARRAY);

  array_length = rb_long2int(RARRAY_LEN(self));

  if (array_length <= 0)
  {
    rb_raise(rb_eRangeError, "array must have at least one element");
  }

  return DBL2NUM(calculate_mean(self, array_length));
}

#medianObject



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;
}