Skip to content

Commit b7bae8e

Browse files
committed
Added 'Newton method' for interpolation
1 parent db1399e commit b7bae8e

3 files changed

Lines changed: 47 additions & 0 deletions

File tree

README.md

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

5353
- Lagrange method
54+
- Newton method
5455
- Neville method
5556

5657
### Algorithms for polynomials

interpolation.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,33 @@ def lagrange(x, y, x_int):
2727
return [y_int]
2828

2929

30+
def newton(x, y, x_int):
31+
"""Interpolates a value using the 'Newton polynomial'.
32+
33+
Args:
34+
x (numpy.ndarray): x values.
35+
y (numpy.ndarray): y values.
36+
x_int (float): value to interpolate.
37+
38+
Returns:
39+
y_int (float): interpolated value.
40+
"""
41+
m = x.size
42+
del_y = y.copy()
43+
44+
# Calculate the divided differences
45+
for k in range(1, m):
46+
for i in range(m - 1, k - 1, -1):
47+
del_y[i] = (del_y[i] - del_y[i - 1]) / (x[i] - x[i - k])
48+
49+
# Evaluate the Newton polynomial
50+
y_int = del_y[-1]
51+
for i in range(m - 2, -1, -1):
52+
y_int = y_int * (x_int - x[i]) + del_y[i]
53+
54+
return [y_int]
55+
56+
3057
def neville(x, y, x_int):
3158
"""Interpolates a value using the 'Neville polynomial'.
3259

main.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,24 @@ def run_example_lagrange():
239239
print(f"y_int = {y_int:.5f}")
240240

241241

242+
@print_docstring
243+
def run_interpolation_newton():
244+
"""Run an example 'Interpolation: Newton'."""
245+
x = np.array([0.1, 0.3, 0.4, 0.6, 0.7])
246+
y = np.array([0.3162, 0.5477, 0.6325, 0.7746, 0.8367])
247+
x_int = 0.2
248+
249+
print("Inputs:")
250+
print(f"x = {x}")
251+
print(f"y = {y}")
252+
print(f"x_int = {x_int}")
253+
254+
[y_int] = interpolation.newton(x, y, x_int)
255+
256+
print("Output:")
257+
print(f"y_int = {y_int:.5f}")
258+
259+
242260
@print_docstring
243261
def run_example_neville():
244262
"""Run an example 'Interpolation: Neville'."""
@@ -679,6 +697,7 @@ def main():
679697
run_example_muller()
680698
run_example_newton()
681699
run_example_lagrange()
700+
run_interpolation_newton()
682701
run_example_neville()
683702
run_example_root_limits()
684703
run_example_briot_ruffini()

0 commit comments

Comments
 (0)