#!/usr/bin/ruby -w

module Num
  def integrate(from, to, n = 1000)
    from, to = from.to_f, to.to_f  
    dx = (to - from) / n
    x = from + dx / 2 # mid point method
    sum = 0.0

    n.times do
      sum += yield(x)
      x += dx
    end

    return sum * dx
  end

  module_function :integrate
end

include Math, Num
p integrate(0, PI/2) { |x| cos(x) } # => 1.000000103
