Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list
(x_points: list, y_points: list, x0: int)
| 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 | ... |
| 35 | TypeError: unsupported operand type(s) for -: 'str' and 'int' |
| 36 | """ |
| 37 | n = len(x_points) |
| 38 | q = [[0] * n for i in range(n)] |
| 39 | for i in range(n): |
| 40 | q[i][1] = y_points[i] |
| 41 | |
| 42 | for i in range(2, n): |
| 43 | for j in range(i, n): |
| 44 | q[j][i] = ( |
| 45 | (x0 - x_points[j - i + 1]) * q[j][i - 1] |
| 46 | - (x0 - x_points[j]) * q[j - 1][i - 1] |
| 47 | ) / (x_points[j] - x_points[j - i + 1]) |
| 48 | |
| 49 | return [q[n - 1][n - 1], q] |
| 50 | |
| 51 | |
| 52 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected