Class: Silicium::Algebra::PolynomialInterpolation

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

Overview

A class providing polynomial interpolation methods

Class Method Summary collapse

Class Method Details

.check_arrays(x, y) ⇒ Object

helper for helper



64
65
66
67
68
69
70
# File 'lib/polynomial_interpolation.rb', line 64

def self.check_arrays(x, y)

  if x.size < 2  ||  x.size < 2
    raise ArgumentError, 'Arrays are too small'
  end

end

.check_types(x, y, z) ⇒ Object

helper for helper



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/polynomial_interpolation.rb', line 73

def self.check_types(x, y, z)

  if x.class != Array || y.class != Array
    raise ArgumentError, 'Wrong type of variables x or y'
  end

  if z.class.superclass != Numeric
    raise ArgumentError, 'Wrong type of variable z'
  end

  if x[0].class.superclass != Numeric || y[0].class.superclass != Numeric
    raise ArgumentError, 'Wrong type of arrays'
  end

end

.check_variables(x, y, z) ⇒ Object

helper



58
59
60
61
# File 'lib/polynomial_interpolation.rb', line 58

def self.check_variables(x, y, z)
  check_types(x, y, z)
  check_arrays(x, y)
end

.lagrange_polynomials(x, y, z) ⇒ Object

x : array of data points y : array returned by function z : the node to interpolate



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/polynomial_interpolation.rb', line 12

def self.lagrange_polynomials(x , y , z )
  check_variables(x, y, z)
  result = 0.0
  y.each_index do |j|
    p1 = 1.0
    p2 = 1.0
    x.each_index do |i|
      if i != j
        p1 = p1 * (z - x[i])
        p2 = p2 * (x[j] - x[i])
      end
    end
    result = result + y[j] * p1 / p2
  end
  result
end

.newton_polynomials(x, y, r) ⇒ Object

x : array of data points y : array returned by function r : the node to interpolate



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/polynomial_interpolation.rb', line 33

def self.newton_polynomials(x, y, r)
  check_variables(x, y, r)
  a = Array[]
  y.each do |elem|
    a << elem
  end
  for j in 1..x.length - 1
    i = x.length - 1
    while i != j - 1
      a[i] = (a[i] - a[i - 1]) / (x[i] - x[i - j])
      i -= 1
    end
  end

  n = a.length - 1
  res = a[n]
  i = n - 1
  while i != -1
    res = res * (r - x[i]) + a[i]
    i -= 1
  end
  res
end