Advertisement
Python253

newton_polynomial_interpolation

May 23rd, 2024
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.16 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: newton_polynomial_interpolation.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script demonstrates polynomial interpolation using Newton's divided differences method.
  10.    - It allows users to input their own data points and visualizes the interpolating polynomial.
  11.  
  12. Requirements:
  13.    - Python 3.x
  14.    - NumPy
  15.    - Matplotlib
  16.  
  17. Functions:
  18.    - newtdd:
  19.        Computes coefficients of interpolating polynomial using Newton's divided differences method.
  20.    - nest:
  21.        Evaluates the interpolating polynomial at a specific point.
  22.    - newton_poly:
  23.        Evaluates the Newton polynomial at specific points.
  24.    - main:
  25.        Main function to execute polynomial interpolation.
  26.  
  27. Usage:
  28.    - Run the script and follow the prompts to input data points.
  29.  
  30. Expected Example Output:
  31.    - The script will plot the interpolating polynomial along with the data points provided by the user.
  32.  
  33. Additional Notes:
  34.    - Ensure NumPy and Matplotlib are installed in your Python environment.
  35. """
  36.  
  37. import numpy as np
  38. import matplotlib.pyplot as plt
  39.  
  40. def newtdd(x_values, y_values, n):
  41.     """
  42.    Calculate coefficients of interpolating polynomial using Newton's divided differences method.
  43.  
  44.    Parameters:
  45.        x_values (ndarray):
  46.            Array of x-coordinates of data points.
  47.        y_values (ndarray):
  48.            Array of y-coordinates of data points.
  49.        n (int):
  50.            Number of data points.
  51.  
  52.    Returns:
  53.        ndarray: Coefficients of the interpolating polynomial.
  54.    """
  55.     v = np.zeros((n, n))
  56.     for j in range(n):
  57.         v[j][0] = y_values[j]
  58.     for i in range(1, n):
  59.         for j in range(n - i):
  60.             v[j][i] = (v[j+1][i-1] - v[j][i-1]) / (x_values[i+j] - x_values[j])
  61.     return v[0]
  62.  
  63. def nest(c, x_values, t):
  64.     """
  65.    Evaluate the interpolating polynomial at a specific point.
  66.  
  67.    Parameters:
  68.        c (ndarray):
  69.            Coefficients of the interpolating polynomial.
  70.        x_values (ndarray):
  71.            Array of x-coordinates of data points.
  72.        t (float):
  73.            Point at which to evaluate the polynomial.
  74.  
  75.    Returns:
  76.        float: Value of the polynomial at point t.
  77.    """
  78.     n = len(c)
  79.     result = c[-1]
  80.     for i in range(2, n+1):
  81.         result = result * (t - x_values[n-i]) + c[n-i]
  82.     return result
  83.  
  84. def newton_poly(coef, x_data, x):
  85.     """
  86.    Evaluate the Newton polynomial at x.
  87.  
  88.    Parameters:
  89.        coef (ndarray):
  90.            Coefficients of the interpolating polynomial.
  91.        x_data (ndarray):
  92.            Array of x-coordinates of data points.
  93.        x (ndarray):
  94.            Points at which to evaluate the polynomial.
  95.  
  96.    Returns:
  97.        ndarray: Value of the polynomial at points x.
  98.    """
  99.     n = len(x_data) - 1
  100.     p = coef[n]
  101.     for k in range(1, n + 1):
  102.         p = coef[n-k] + (x - x_data[n-k]) * p
  103.     return p
  104.  
  105. def main():
  106.     """
  107.    Main function to execute polynomial interpolation.
  108.    """
  109.     print("Welcome to Polynomial Interpolation using Newton's divided differences method!")
  110.     n = int(input("\nEnter the number of data points: "))
  111.     x_values = np.zeros(n)
  112.     y_values = np.zeros(n)
  113.     print("\nEnter the data points:")
  114.     for i in range(n):
  115.         x_values[i] = float(input(f"Enter x{i+1}: "))
  116.         y_values[i] = float(input(f"Enter y{i+1}: "))
  117.  
  118.     coefficients = newtdd(x_values, y_values, n)
  119.  
  120.     # Evaluate the interpolating polynomial at specific points
  121.     x_new = np.linspace(min(x_values), max(x_values), 500)
  122.     y_new = nest(coefficients, x_values, x_new)
  123.  
  124.     # Plot the results
  125.     plt.plot(x_new, y_new, label='Interpolating Polynomial')
  126.     plt.scatter(x_values, y_values, color='red', label='Data Points')
  127.     plt.xlabel('x')
  128.     plt.ylabel('y')
  129.     plt.title('Newton Polynomial Interpolation')
  130.     plt.legend()
  131.  
  132.     # Annotate each data point with its corresponding coordinates
  133.     for i, (x, y) in enumerate(zip(x_values, y_values)):
  134.         plt.text(x, y, f'({x}, {y})', fontsize=10, ha='right', va='bottom')
  135.  
  136.     plt.grid(True)
  137.     plt.show()
  138.  
  139. if __name__ == "__main__":
  140.     main()
  141.  
  142.  
  143.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement