-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathinterpolation.py
109 lines (81 loc) · 2.6 KB
/
interpolation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""Methods for Interpolation."""
import numpy as np
def lagrange(x, y, x_int):
"""Interpolates a value using the 'Lagrange polynomial'.
Args:
x (numpy.ndarray): x values.
y (numpy.ndarray): y values.
x_int (float): value to interpolate.
Returns:
y_int (float): interpolated value.
"""
m = x.size
y_int = 0
for i in range(0, m):
p = y[i]
for j in range(0, m):
if i != j:
p = p * (x_int - x[j]) / (x[i] - x[j])
y_int = y_int + p
return y_int
def newton(x, y, x_int):
"""Interpolates a value using the 'Newton polynomial'.
Args:
x (numpy.ndarray): x values.
y (numpy.ndarray): y values.
x_int (float): value to interpolate.
Returns:
y_int (float): interpolated value.
"""
m = x.size
del_y = y.copy()
# Calculate the divided differences
for k in range(1, m):
for i in range(m - 1, k - 1, -1):
del_y[i] = (del_y[i] - del_y[i - 1]) / (x[i] - x[i - k])
# Evaluate the polynomial by Horner's method
y_int = del_y[-1]
for i in range(m - 2, -1, -1):
y_int = y_int * (x_int - x[i]) + del_y[i]
return y_int
def gregory_newton(x, y, x_int):
"""Interpolates a value using the 'Gregory-Newton polynomial'.
Args:
x (numpy.ndarray): x values.
y (numpy.ndarray): y values.
x_int (float): value to interpolate.
Returns:
y_int (float): interpolated value.
"""
m = x.size
del_y = y.copy()
# Calculate the finite differences
for k in range(1, m):
for i in range(m - 1, k - 1, -1):
del_y[i] = del_y[i] - del_y[i - 1]
# Evaluate the polynomial by Horner's method
u = (x_int - x[0]) / (x[1] - x[0])
y_int = del_y[-1]
for i in range(m - 2, -1, -1):
y_int = y_int * (u - i) / (i + 1) + del_y[i]
return y_int
def neville(x, y, x_int):
"""Interpolates a value using the 'Neville polynomial'.
Args:
x (numpy.ndarray): x values.
y (numpy.ndarray): y values.
x_int (float): value to interpolate.
Returns:
y_int (float): interpolated value.
q (numpy.ndarray): coefficients matrix.
"""
n = x.size
q = np.zeros((n, n - 1))
# Insert 'y' in the first column of the matrix 'q'
q = np.concatenate((y[:, None], q), axis=1)
for i in range(1, n):
for j in range(1, i + 1):
q[i, j] = ((x_int - x[i - j]) * q[i, j - 1] -
(x_int - x[i]) * q[i - 1, j - 1]) / (x[i] - x[i - j])
y_int = q[n - 1, n - 1]
return y_int, q