Sha256: 1e7cf0d6f9c777b14c9d3f5fc27f834bca0c437218cd1ac473aa20547f7c4f1d

Contents?: true

Size: 749 Bytes

Versions: 5

Compression:

Stored size: 749 Bytes

Contents

require 'inline'

class Array
  # this is incredibly faster than doing ary.inject(0, :+)
  # should only be called on numbers-only arrays, though ;-)
  inline :C do |builder|
    builder.c_raw <<-EOC
    static VALUE sum(int argc, VALUE *argv, VALUE self) {
      double result = 0;
      VALUE *arr = RARRAY_PTR(self);
      long i, len = RARRAY_LEN(self);

      for (i = 0; i < len; i++) {
        result += NUM2DBL(arr[i]);
      }

      return rb_float_new(result);
    }
    EOC
  end

  def mean
    sum.to_f / length
  end

  def variance
    m = mean
    reduce(0) {|accum, item| accum + (item - m) ** 2}.to_f / (length - 1)
  end

  def stdev
    Math.sqrt(variance)
  end

  def percentile(pc)
    sort[(pc * length).ceil - 1]
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ganymed-0.3.4 lib/ganymed/ext/array.rb
ganymed-0.3.3 lib/ganymed/ext/array.rb
ganymed-0.3.2 lib/ganymed/ext/array.rb
ganymed-0.3.1 lib/ganymed/ext/array.rb
ganymed-0.3.0 lib/ganymed/ext/array.rb