Python Forum
programming an interpolation polynom relating newton - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: programming an interpolation polynom relating newton (/thread-30940.html)



programming an interpolation polynom relating newton - Hallo810 - Nov-14-2020

Hello,
i try to programm an interpolation polynom relating newton. I get an interpolation polynom with the values, which is outcommented in the main-method. My problem is to get an interpolationpolynom with the values of an excel list. At the moment I receive the graph of the values without the interolationpolynom and I obtain this error message:
Error:
e:/Python Skripte/test2.py:34: RuntimeWarning: overflow encountered in double_scalars counter = counter * (X[i] - X[k-1]) e:/Python Skripte/test2.py:75: RuntimeWarning: invalid value encountered in double_scalars C[i] = (Y[i] - sum) / A[i][i] e:/Python Skripte/test2.py:74: RuntimeWarning: invalid value encountered in double_scalars sum = sum + A[i][j] * C[j]
My python code is following:
import pandas as pd
import numpy as np
import numpy.linalg
import matplotlib.pyplot as plt

#Datensatz importieren
dataset = pd.read_excel('Path\...\data.xlsx')
values = dataset.values

valuesX = np.zeros(len(values))
for i in range(len(values)):
    valuesX[i] = values[i][0]

valuesY = np.zeros(len(values))
for j in range(len(values)):
    valuesY[j] = values[j][1]

#print(valuesY[:])

def newton_matrix(X):
    # """Setup the matrix of the LSE which is used to determine the coefficients
    # of the Newton-basis.  X are the x-coordinates of the nodes which are
    # used for interpolation."""
    # Matrix zweidimensional mit Nullen fuellen und 1. Spalte mit 1
    result = np.zeros((len(X), len(X)))
    for a in range(0, len(result)):
        result[a][0] = 1
    # zeilenmaessiges Befuellen der Matrix mit den entsprechenden Polynomen
    for i in range(1, len(result)):
        for j in range(1, i+1):
            counter = 1
            for k in range(1, j+1):
                counter = counter * (X[i] - X[k-1])
            result[i][j] = counter

    return result



def newton_polynomial(C, X):
    # """Take coefficients and interpolation point x-coordinates of the
    # Newton-polynomial and determine the corresponding interpolation polynomial."""
    # Bedingung muss erfuellt sein, ansonsten Abbruch der Methode
    assert len(C) == len(X)

    # Anlegen des Newton-Polynom; Methode poly1d erstellt ein Polynom mithilfe von True gibt er die faktorisierte
    # Form an
    result = np.poly1d([])

    # Erstellen des Interpolationspolynoms nach Newton; np.poly1d gibt fuer eine leere Liste 1 heraus
    for i in range(0, len(C)):
        X_new = []
        for j in range(0, i):
            X_new.append(X[j])
        X_poly = np.poly1d(X_new, True)
        result = result + C[i] * X_poly

    return result


def interpolating_polynomial(X,Y):
    #"""Determine the interpolating polynomial for the given NumPy arrays of x and y coordinates."""
    # Pruefen, ob Bedingung erfuellt wird, ansonsten Abbruch der Methode
    assert len(X) == len(Y)
    # Erstellen der Matrix A
    A = newton_matrix(X)
    # Erstellen des Vektors C
    C = np.zeros(len(A))
    # Koeffizienten des Newton-Polynoms bestimmen und als Polynom darstellen
    for i in range(len(A)):
        sum = 0
        for j in range(len(A)):
            sum = sum + A[i][j] * C[j]
        C[i] = (Y[i] - sum) / A[i][i]
    result = newton_polynomial(C, X)
    return result


def interpolation_plot(X,Y):
    p = interpolating_polynomial(X, Y)
    px = np.arange(min(X)-0.1, max(X)+0.11, 0.01)
    plt.grid(True)
    plt.plot(X, Y, "o")
    plt.plot(px, p(px))
    plt.show()


def main():
   # newton_matrix(np.array([-2., 0., 2.]))
   
   # X = np.array([0, 1, 2,3])
   # Y = np.array([-2.,3.,1.,2.])
    
    X = valuesX
    Y = valuesY
    interpolation_plot(X, Y)

if __name__ == "__main__": main()
In my ecxel list I have 215 x-values and 215 y-values.

Has anybody an idea?

Thank you very much.

Best regards


RE: programming an interpolation polynom relating newton - buran - Nov-14-2020

don't know about the error, but don't use sum as name, it's a built-in function and you override it