MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / interpolate

Function interpolate

project_euler/problem_101/sol1.py:113–161  ·  view source on GitHub ↗

Given a list of data points (1,y0),(2,y1), ..., return a function that interpolates the data points. We find the coefficients of the interpolating polynomial by solving a system of linear equations corresponding to x = 1, 2, 3... >>> interpolate([1])(3) 1 >>> interpolat

(y_list: list[int])

Source from the content-addressed store, hash-verified

111
112
113def interpolate(y_list: list[int]) -> Callable[[int], int]:
114 """
115 Given a list of data points (1,y0),(2,y1), ..., return a function that
116 interpolates the data points. We find the coefficients of the interpolating
117 polynomial by solving a system of linear equations corresponding to
118 x = 1, 2, 3...
119
120 >>> interpolate([1])(3)
121 1
122 >>> interpolate([1, 8])(3)
123 15
124 >>> interpolate([1, 8, 27])(4)
125 58
126 >>> interpolate([1, 8, 27, 64])(6)
127 216
128 """
129
130 size: int = len(y_list)
131 matrix: Matrix = [[0 for _ in range(size)] for _ in range(size)]
132 vector: Matrix = [[0] for _ in range(size)]
133 coeffs: Matrix
134 x_val: int
135 y_val: int
136 col: int
137
138 for x_val, y_val in enumerate(y_list):
139 for col in range(size):
140 matrix[x_val][col] = (x_val + 1) ** (size - col - 1)
141 vector[x_val][0] = y_val
142
143 coeffs = solve(matrix, vector)
144
145 def interpolated_func(var: int) -> int:
146 """
147 >>> interpolate([1])(3)
148 1
149 >>> interpolate([1, 8])(3)
150 15
151 >>> interpolate([1, 8, 27])(4)
152 58
153 >>> interpolate([1, 8, 27, 64])(6)
154 216
155 """
156 return sum(
157 round(coeffs[x_val][0]) * (var ** (size - x_val - 1))
158 for x_val in range(size)
159 )
160
161 return interpolated_func
162
163
164def question_function(variable: int) -> int:

Callers 1

solutionFunction · 0.85

Calls 1

solveFunction · 0.70

Tested by

no test coverage detected