Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import matplotlib.pyplot as plt
- def lagrange_interpolation(x_data, y_data, x_val):
- """
- This function performs Lagrange polynomial interpolation for a given set of data points.
- Args:
- x_data: A list or numpy array containing the x-coordinates of the data points.
- y_data: A list or numpy array containing the corresponding y-values of the data points.
- x_val: The value at which to evaluate the interpolated polynomial.
- Returns:
- The interpolated value of the function at x_val.
- """
- n = len(x_data)
- result = 0
- for i in range(n):
- basis_poly = 1
- for j in range(n):
- if j != i:
- basis_poly *= (x_val - x_data[j]) / (x_data[i] - x_data[j])
- result += y_data[i] * basis_poly
- return result
- def plot_interpolation(x_data, y_data, x_range):
- """
- This function plots the original data points and the interpolated polynomial.
- Args:
- x_data: A list or numpy array containing the x-coordinates of the data points.
- y_data: A list or numpy array containing the corresponding y-values of the data points.
- x_range: A tuple containing the minimum and maximum values for the x-axis.
- """
- # Generate interpolated points
- x_interp = np.linspace(x_range[0], x_range[1], 100) # Adjust number of points as needed
- y_interp = [lagrange_interpolation(x_data, y_data, x) for x in x_interp]
- # Plot data points and interpolated function
- plt.plot(x_data, y_data, 'o', label='Data Points')
- plt.plot(x_interp, y_interp, label='Interpolated Polynomial')
- # Set labels and title
- plt.xlabel("X")
- plt.ylabel("Y")
- plt.title("Lagrange Polynomial Interpolation")
- plt.legend()
- plt.grid(True)
- plt.show()
- # Example usage
- 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
- 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
- # Define x-axis range for plotting
- x_range = (min(x_data), max(x_data))
- # Calculate interpolated points and plot
- plot_interpolation(x_data, y_data, x_range)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement