Method: Math.simpson_rule

Defined in:
lib/math.rb

.simpson_rule(a, b, n, &block) ⇒ Object

Function adapted from the python implementation that exists in en.wikipedia.org/wiki/Simpson%27s_rule#Sample_implementation Finite integral in the interval [a, b] split up in n-intervals



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/math.rb', line 21

def self.simpson_rule(a, b, n, &block)
  unless n.even?
    puts "The composite simpson's rule needs even intervals!"
    return
  end

  h = (b - a)/n.to_f
  resA = yield(a)
  resB = yield(b)

  sum = resA + resB

  (1..n).step(2).each do |number|
    res = yield(a + number * h)
    sum += 4 * res
  end

  (1..(n-1)).step(2).each do |number|
    res = yield(a + number * h)
    sum += 2 * res
  end

  return sum * h / 3.0
end