Skip to content

Commit db33c28

Browse files
authored
Merge pull request #1 from hacquees/agrange_interpolation
Create lagrange_interpolation.py
2 parents fe4aad0 + 4e12330 commit db33c28

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import math
2+
from typing import List
3+
4+
def lagrange_interpolation(x: List[float], y: List[float], value: float) -> float:
5+
"""
6+
Calculate the Lagrange interpolation of a function based on provided data points.
7+
8+
Parameters:
9+
x (List[float]): List of x-values (independent variable).
10+
y (List[float]): List of corresponding y-values (dependent variable).
11+
value (float): The value at which to interpolate the function.
12+
13+
Returns:
14+
float: The interpolated value of the function at the specified 'value'.
15+
16+
for eg.:
17+
18+
>>> x = [5, 6, 9, 11]
19+
>>> y = [12, 13, 14, 16]
20+
>>> lagrange_interpolation(x, y, 10)
21+
14.666666666666666
22+
23+
"""
24+
ans = 0
25+
n = len(x)
26+
27+
for i in range(n):
28+
term = y[i]
29+
for j in range(n):
30+
if i != j:
31+
term *= (value - x[j]) / (x[i] - x[j])
32+
ans += term
33+
34+
return ans
35+
36+
def main():
37+
"""
38+
Main function for performing Lagrange interpolation.
39+
Takes user input for data points and the value to interpolate, then displays the interpolated result.
40+
"""
41+
n = int(input("Enter the number of values: "))
42+
x = []
43+
y = []
44+
45+
print("Enter the values of x in a list: ")
46+
x = list(map(float, input().split()))
47+
48+
print("Enter the values of corresponding y: ")
49+
y = list(map(float, input().split()))
50+
51+
value_to_interpolate = float(input("Enter the value to interpolate:"))
52+
53+
interpolated_value = lagrange_interpolation(x, y, value_to_interpolate)
54+
55+
print(f"The interpolated value at {value_to_interpolate} is {interpolated_value}")
56+
57+
if __name__ == "__main__":
58+
main()

0 commit comments

Comments
 (0)