Class: MadMath::NewtonPolynomial

Inherits:
Object
  • Object
show all
Defined in:
lib/mad_math/newton_polynomial.rb

Instance Method Summary collapse

Constructor Details

#initialize(data = []) ⇒ NewtonPolynomial

Returns a new instance of NewtonPolynomial.



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/mad_math/newton_polynomial.rb', line 3

def initialize(data = [])
  @xs = []
  @ys = []
  @calc = []

  #pp data
  #puts '-' * 80

  data.each do |el|
    raise "Element is missing." if el.length != 2
    add el.first, el.last
  end
end

Instance Method Details

#add(x, y) ⇒ Object



17
18
19
20
21
22
# File 'lib/mad_math/newton_polynomial.rb', line 17

def add(x, y)
  @xs << x
  @ys << y

  calc(x) if @xs.length > 1
end

#value_for(x) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/mad_math/newton_polynomial.rb', line 24

def value_for(x)
  y = @ys.first
  #print "#{@ys.first} + "
  @calc.each_with_index do |col, i|
    #print "#{col[0]}"
    xs = (i + 1).times.to_a.map do |j|
      #print " * (#{x} - #{@xs[j]})"
      x - @xs[j]
    end.reduce(:*)
    y += col[0] * xs
    #print " + "
  end
  #puts
  #puts '=' * 80
  y
end