This document contains code to perform Lagrange polynomial interpolation on a dataset. It defines x and y value arrays, initializes a result polynomial to 0, calculates the Lagrange basis polynomials and linear combination to determine the result polynomial, prints the result, evaluates it at additional x values, and plots the dataset points and polynomial on a graph.
This document contains code to perform Lagrange polynomial interpolation on a dataset. It defines x and y value arrays, initializes a result polynomial to 0, calculates the Lagrange basis polynomials and linear combination to determine the result polynomial, prints the result, evaluates it at additional x values, and plots the dataset points and polynomial on a graph.
This document contains code to perform Lagrange polynomial interpolation on a dataset. It defines x and y value arrays, initializes a result polynomial to 0, calculates the Lagrange basis polynomials and linear combination to determine the result polynomial, prints the result, evaluates it at additional x values, and plots the dataset points and polynomial on a graph.
This document contains code to perform Lagrange polynomial interpolation on a dataset. It defines x and y value arrays, initializes a result polynomial to 0, calculates the Lagrange basis polynomials and linear combination to determine the result polynomial, prints the result, evaluates it at additional x values, and plots the dataset points and polynomial on a graph.
Download as DOCX, PDF, TXT or read online from Scribd
Download as docx, pdf, or txt
You are on page 1of 1
import scipy
import matplotlib.pyplot as plt
import numpy as np
x = scipy.array([0.1,0.3, 0.5, 0.7, 0.9,1.1,1.3])
y = scipy.array([0.030, 0.067, 0.148, 0.248, 0.320,0.518, 0.697]) result = scipy.poly1d([0.0]) # setting result = 0
for i in range(0, len(x)): # number of polynomials L_k(x).
temp_numerator = scipy.poly1d([1.0]) # resets temp_numerator such that a new #numerator can be created for each i. denumerator = 1.0 # resets denumerator such that a new denumerator can be #created for each i. for j in range(0, len(x)): if i != j: temp_numerator *= scipy.poly1d([1.0, -x[j]]) # finds numerator for L_i denumerator *= x[i] - x[j] # finds denumerator for L_i result += (temp_numerator / denumerator) * y[i] # linear combination
print("The result is: ")
print(result)
#SOAL NO 2
p=scipy.array([0.365, 0.512, 0.621, 0.715])
for z in range (0,len(p)): a=result(p[z]) print('untuk x = ',p[z],'maka y = ',a)
x_val = np.arange(min(x), max(x) + 1, 0.1) # generates x values we would like to
evaluate. plt.xlabel('x'); plt.ylabel('p(x)') plt.grid(True) for i in range(0, len(x)): plt.plot([x[i]], [y[i]], 'ro') # plot the points plt.plot(x_val, result(x_val)) # result(x_val) gives the value of our Lagrange polynomial. plt.axis([min(x) - 1, max(x) + 1, min(y) - 1, max(y) + 1]) plt.show()