Skip to content

Commit d6c606f

Browse files
committed
Added 'Gregory-Newton method'
1 parent cd9ab34 commit d6c606f

3 files changed

Lines changed: 49 additions & 1 deletion

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ python3 main.py
5252

5353
- Lagrange method
5454
- Newton method
55+
- Gregory-Newton method
5556
- Neville method
5657

5758
### Algorithms for polynomials

interpolation.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,42 @@ def newton(x, y, x_int):
4646
for i in range(m - 1, k - 1, -1):
4747
del_y[i] = (del_y[i] - del_y[i - 1]) / (x[i] - x[i - k])
4848

49-
# Evaluate the Newton polynomial
49+
# Evaluate the polynomial by Horner's method
5050
y_int = del_y[-1]
5151
for i in range(m - 2, -1, -1):
5252
y_int = y_int * (x_int - x[i]) + del_y[i]
5353

5454
return [y_int]
5555

5656

57+
def gregory_newton(x, y, x_int):
58+
"""Interpolates a value using the 'Gregory-Newton polynomial'.
59+
60+
Args:
61+
x (numpy.ndarray): x values.
62+
y (numpy.ndarray): y values.
63+
x_int (float): value to interpolate.
64+
65+
Returns:
66+
y_int (float): interpolated value.
67+
"""
68+
m = x.size
69+
del_y = y.copy()
70+
71+
# Calculate the finite differences
72+
for k in range(1, m):
73+
for i in range(m - 1, k - 1, -1):
74+
del_y[i] = del_y[i] - del_y[i - 1]
75+
76+
# Evaluate the polynomial by Horner's method
77+
u = (x_int - x[0]) / (x[1] - x[0])
78+
y_int = del_y[-1]
79+
for i in range(m - 2, -1, -1):
80+
y_int = y_int * (u - i) / (i + 1) + del_y[i]
81+
82+
return [y_int]
83+
84+
5785
def neville(x, y, x_int):
5886
"""Interpolates a value using the 'Neville polynomial'.
5987

main.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,24 @@ def example_interpolation_newton():
257257
print(f"y_int = {y_int:.5f}")
258258

259259

260+
@print_docstring
261+
def example_interpolation_gregory_newton():
262+
"""Run an example 'Interpolation: Gregory-Newton'."""
263+
x = np.array([110, 120, 130])
264+
y = np.array([2.0410, 2.0790, 2.1140])
265+
x_int = 115
266+
267+
print("Inputs:")
268+
print(f"x = {x}")
269+
print(f"y = {y}")
270+
print(f"x_int = {x_int}")
271+
272+
[y_int] = interpolation.gregory_newton(x, y, x_int)
273+
274+
print("Output:")
275+
print(f"y_int = {y_int:.5f}")
276+
277+
260278
@print_docstring
261279
def example_interpolation_neville():
262280
"""Run an example 'Interpolation: Neville'."""
@@ -703,6 +721,7 @@ def main():
703721
# Interpolation
704722
example_interpolation_lagrange()
705723
example_interpolation_newton()
724+
example_interpolation_gregory_newton()
706725
example_interpolation_neville()
707726

708727
# Algorithms for polynomials

0 commit comments

Comments
 (0)