I am trying to make a Lagrange function but when I print it it doesn't show how it would be if the multiplications were to happen. My code is as follows:
import numpy as np
from matplotlib.pyplot import plot, show, grid
import numpy.polynomial.polynomial as poly
import matplotlib.pyplot as plt
from scipy.interpolate import lagrange
from sympy import symbols, Eq
x1 = [120, 180, 270, 300] # x
y1 = [246, 351, 514, 572] # y
def Lagrange(Lx, Ly):
x = symbols('x')
y = 0
for k in range(len(Lx)):
p = 1
for j in range(len(Lx)):
if j != k:
p = p * ((x - Lx[j]) / (Lx[k] - Lx[j]))
y = p * Ly[k]
return y
print(Lagrange(x1, y1))
poly=lagrange(x1,y1)
print(poly)
At the output I get this:
246*(5/3 - x/180)*(9/5 - x/150)*(3 - x/60) 351*(5/2 - x/120)*(3 - x/90)*(x/60 - 2) 514*(10 - x/30)*(x/150 - 4/5)*(x/90 - 2) 572*(x/180 - 2/3)*(x/120 - 3/2)*(x/30 - 9)
where I would prefer something like this:
3 2
3.395e-06 x - 0.001528 x 1.976 x 25
CodePudding user response:
Use the simplify
function
...
from sympy import simplify
...
...
print(Lagrange(x1, y1))
poly=simplify(lagrange(x1,y1))
print(poly)