Class: ChebyRuby::SimpsonsIntegration

Inherits:
Object
  • Object
show all
Includes:
Integration
Defined in:
lib/chebyruby/simpsons_integration.rb

Overview

This class is for the composite Simpson’s rule. The Composite Simpson’s rule involves summing Simpson’s rule being calculated over a fine mesh.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(func) ⇒ SimpsonsIntegration

Basic constructor for SimpsonsIntegration. It can be implemented in two ways. It can either have a UnivariateFunction passed to it or a proc.

Parameters:



16
17
18
19
20
21
22
# File 'lib/chebyruby/simpsons_integration.rb', line 16

def initialize(func)
  if func.is_a? Proc
    @func = UnivariateFunction.new(&func)
  else
    @func = func
  end
end

Instance Attribute Details

#funcUnivariateFunction

the function over which to integrate.

Returns:



7
8
9
# File 'lib/chebyruby/simpsons_integration.rb', line 7

def func
  @func
end

Instance Method Details

#accuracy_comparison(a, b, method = 'Trapezoid') ⇒ Float

This method compares the accuate of Simpsons to other methods.

Parameters:

  • a (Numeric)

    the lower bounds of the integral

  • b (Numeric)

    the upper bounds of the integral

  • method (String) (defaults to: 'Trapezoid')

    the method to compare to

Returns:

  • (Float)

    the absolute difference between the two methods.



46
47
48
# File 'lib/chebyruby/simpsons_integration.rb', line 46

def accuracy_comparison(a, b, method = 'Trapezoid')
  super.accuracy_comparison(a, b, method, 'Simpsons')
end

#integrate(a, b, iterations = 32) ⇒ Object

This method integrates the function parameter using the composite simpsons rule.

Parameters:

  • a (Numeric)

    the lower bounds of the integral

  • b (Numeric)

    the upper bounds of the integral

  • iterations (Integer) (defaults to: 32)

    the number of iterations to be used for integration.



30
31
32
33
34
35
36
37
38
# File 'lib/chebyruby/simpsons_integration.rb', line 30

def integrate(a, b, iterations = 32)
  h = (b - a) / iterations.to_f
  mesh = (a..b).step(h).to_a[1...-1]
  even = mesh.each_with_index.select{|i, j| j.odd?}.map(&:first)
  odd = mesh.each_with_index.select{|i, j| j.even?}.map(&:first)
  summand = func.value(a) + func.value(b) +
      2 * even.map(&func.func).inject(:+) + 4 * odd.map(&func.func).inject(:+)
  (h / 3.0) * summand
end