|
| 1 | +""" |
| 2 | + Python program to show how to interpolate and evaluate a polynomial |
| 3 | + using Neville's method. |
| 4 | + Neville’s method evaluates a polynomial that passes through a |
| 5 | + given set of x and y points for a particular x value (x0) using the |
| 6 | + Newton polynomial form. |
| 7 | + Reference: |
| 8 | + https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: |
| 13 | + """ |
| 14 | + Interpolate and evaluate a polynomial using Neville's method. |
| 15 | + Arguments: |
| 16 | + x_points, y_points: Iterables of x and corresponding y points through |
| 17 | + which the polynomial passes. |
| 18 | + x0: The value of x to evaluate the polynomial for. |
| 19 | + Return Value: A list of the approximated value and the Neville iterations |
| 20 | + table respectively. |
| 21 | + >>> import pprint |
| 22 | + >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] |
| 23 | + 10.0 |
| 24 | + >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) |
| 25 | + [[0, 6, 0, 0, 0], |
| 26 | + [0, 7, 0, 0, 0], |
| 27 | + [0, 8, 104.0, 0, 0], |
| 28 | + [0, 9, 104.0, 104.0, 0], |
| 29 | + [0, 11, 104.0, 104.0, 104.0]] |
| 30 | + >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] |
| 31 | + 104.0 |
| 32 | + >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') |
| 33 | + Traceback (most recent call last): |
| 34 | + File "<stdin>", line 1, in <module> |
| 35 | + ... |
| 36 | + TypeError: unsupported operand type(s) for -: 'str' and 'int' |
| 37 | + """ |
| 38 | + n = len(x_points) |
| 39 | + q = [[0] * n for i in range(n)] |
| 40 | + for i in range(n): |
| 41 | + q[i][1] = y_points[i] |
| 42 | + |
| 43 | + for i in range(2, n): |
| 44 | + for j in range(i, n): |
| 45 | + q[j][i] = ( |
| 46 | + (x0 - x_points[j - i + 1]) * q[j][i - 1] |
| 47 | + - (x0 - x_points[j]) * q[j - 1][i - 1] |
| 48 | + ) / (x_points[j] - x_points[j - i + 1]) |
| 49 | + |
| 50 | + return [q[n - 1][n - 1], q] |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + import doctest |
| 55 | + |
| 56 | + doctest.testmod() |
0 commit comments