Ticker

6/recent/ticker-posts

Python Program: Lagrange Interpolation

 Python Program For Lagrange Interpolation

Here is a Python program to calculate the value of a function at a given point using the Lagrange Interpolation Method. Below the program, I provide a step-by-step explanation.
Python Program Lagrange Interpolation


Python Program: Lagrange Interpolation

python
def lagrange_interpolation(x_points, y_points, x): """ Perform Lagrange Interpolation to estimate the value of a function at a given point. :param x_points: List of x-coordinates of the given points :param y_points: List of corresponding y-coordinates of the given points :param x: The point at which to estimate the function value :return: Interpolated value at x """ n = len(x_points) # Number of given points interpolated_value = 0 for i in range(n): # Calculate the ith Lagrange basis polynomial (L_i(x)) L_i = 1 for j in range(n): if i != j: L_i *= (x - x_points[j]) / (x_points[i] - x_points[j]) # Add the contribution of L_i(x) to the final interpolated value interpolated_value += y_points[i] * L_i return interpolated_value # Example Usage x_points = [1, 2, 3] # x-coordinates of known data points y_points = [2, 3, 5] # y-coordinates of known data points x = 2.5 # Point to interpolate result = lagrange_interpolation(x_points, y_points, x) print(f"The interpolated value at x = {x} is {result:.4f}")

Step-by-Step Guide:

  1. Understand Lagrange Interpolation Formula: The formula is:

    P(x)=i=0n1yiLi(x)P(x) = \sum_{i=0}^{n-1} y_i \cdot L_i(x)

    Where Li(x)L_i(x) is the Lagrange basis polynomial given by:

    Li(x)=j=0,jin1xxjxixjL_i(x) = \prod_{j=0, j \neq i}^{n-1} \frac{x - x_j}{x_i - x_j}
  2. Input Data:

    • Define a list of xx-coordinates (x_points) and their corresponding yy-coordinates (y_points).
    • Specify the xx-value where the function should be estimated.
  3. Iterate Over Data Points:

    • For each data point ii, compute Li(x)L_i(x) by iterating over all other points jj.
  4. Compute the Basis Polynomial:

    • Use the formula for Li(x)L_i(x)to calculate the weight of the ii-th data point for the desired xx.
  5. Accumulate Contributions:

    • Multiply Li(x) by yiy_i (the known function value at xix_i) and add it to the total.
  6. Output the Result:

    • After iterating through all points, print the interpolated value at xx.

Example Explanation:

Suppose (x1,y1)=(1,2)(x_1, y_1) = (1, 2), (x2,y2)=(2,3), (x3,y3)=(3,5), and we want to estimate P(2.5)P(2.5):

  1. Compute L0(2.5),L1(2.5),L_0(2.5), L_1(2.5), and L2(2.5)
  2. Multiply each basis polynomial by its corresponding yy-value.
  3. Add all contributions to get the final interpolated value.

Post a Comment

0 Comments