Untitled

unknown
python
2 years ago
1.1 kB
1
Indexable
Never
from sympy import *
import sympy as sy
import numpy as np
import matplotlib.pyplot as plt
#****************************
#-----------------------------
x = symbols("x")
xd = np.array([1.3, 1.6, 1.9])
yd = np.array([0.6200860, 0.4554022, 0.2818186])
yp = np.array([ -0.5220232, -0.5698959, -0.5811571])
xval = 1.5
#******************************
n=len(xd)
H, Hp, PH =0, 0, 0

for k in range(n):
L=1
for i in range(n):
if i != k:
L*=((x-xd[i])/(xd[k]-xd[i]))
Lp = sy.diff(L)
H = ((1-2*(x-xd[k])*Lp.subs(x,xd[k]))*L**2)#*yd[k]
Hp = ((x-xd[k])*L**2)#yp[k]
PH +=H*yd[k]+Hp*yp[k]

print("P(x)=", simplify(PH))
print("P","(x=",xval,")=",PH.subs(x,xval))
#**************************************
fig, ax = plt.subplots()
xplot=np.linspace(xd.mind(),xd.max(),100)
yplot=np.zeros(len(xplot))
Ph=lambdify(x,symplify(PH),np)
ax.plot(xplot,Ph(xplot),'--k', linewidth=1.5)
ax.plot(xval,Ph.subs(x,xval), '*r')
ax.plot(xd,yd,'.',color='crimson')
#**
ax.set_xlabel(r"$\it{x}$", fontsize=12)
ax.set_ylabel(r"$\it{f(x)}$", fontsize=12)
ax.grid(True)