Advertisement
Hustinyano

lagrange.py

May 22nd, 2024
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. def lagrange_interpolation(x_data, y_data, x_val):
  5.   """
  6.  This function performs Lagrange polynomial interpolation for a given set of data points.
  7.  
  8.  Args:
  9.      x_data: A list or numpy array containing the x-coordinates of the data points.
  10.      y_data: A list or numpy array containing the corresponding y-values of the data points.
  11.      x_val: The value at which to evaluate the interpolated polynomial.
  12.  
  13.  Returns:
  14.      The interpolated value of the function at x_val.
  15.  """
  16.   n = len(x_data)
  17.   result = 0
  18.   for i in range(n):
  19.     basis_poly = 1
  20.     for j in range(n):
  21.       if j != i:
  22.         basis_poly *= (x_val - x_data[j]) / (x_data[i] - x_data[j])
  23.     result += y_data[i] * basis_poly
  24.   return result
  25.  
  26. def plot_interpolation(x_data, y_data, x_range):
  27.   """
  28.  This function plots the original data points and the interpolated polynomial.
  29.  
  30.  Args:
  31.      x_data: A list or numpy array containing the x-coordinates of the data points.
  32.      y_data: A list or numpy array containing the corresponding y-values of the data points.
  33.      x_range: A tuple containing the minimum and maximum values for the x-axis.
  34.  """
  35.   # Generate interpolated points
  36.   x_interp = np.linspace(x_range[0], x_range[1], 100)  # Adjust number of points as needed
  37.   y_interp = [lagrange_interpolation(x_data, y_data, x) for x in x_interp]
  38.  
  39.   # Plot data points and interpolated function
  40.   plt.plot(x_data, y_data, 'o', label='Data Points')
  41.   plt.plot(x_interp, y_interp, label='Interpolated Polynomial')
  42.  
  43.   # Set labels and title
  44.   plt.xlabel("X")
  45.   plt.ylabel("Y")
  46.   plt.title("Lagrange Polynomial Interpolation")
  47.   plt.legend()
  48.   plt.grid(True)
  49.   plt.show()
  50.  
  51. # Example usage
  52. x_data = np.array([0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 14.875])  # Replace with your data points
  53. y_data = np.array([0.44, 1.5, 2.875, 4.125, 5.5, 6.875, 8.25, 9.25, 9.375, 9.25, 8.75, 8, 7.375, 6.875, 6.375, 6.375, 6.625, 7.25, 8, 8.25, 7.5, 5.625, 5.25, 5, 5, 5.125, 5.625, 6.375, 7, 7.5, 8.25])  # Replace with your function values at x_data points
  54.  
  55. # Define x-axis range for plotting
  56. x_range = (min(x_data), max(x_data))
  57.  
  58. # Calculate interpolated points and plot
  59. plot_interpolation(x_data, y_data, x_range)
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement