簡體   English   中英

如何在我的拉格朗日插值算法中獲得拉格朗日多項式的 output 而不是其近似值

[英]How do I get output of Lagrange Polynomials instead of its approximation value on my lagrange interpolation algorithm

我有這個程序,它給了我一個近似值的 output。 我如何獲得其拉格朗日多項式的 output。 謝謝

x_points = eval(input('list of point : '))
y_points = eval(input('value : '))
eval_x = eval(input('point that you want to interpolate: '))

def LagrangePol(x,x_points,y_points):
    pol = 0                                                    
    n = len(x_points)                                          
    for k in range(n):
        L = 1                                                  
        for i in range(n):
            if i!=k:
                L*=((x-x_points[i])/(x_points[k]-x_points[i])) 
        pol += y_points[k]*L                                   
    return pol

y_aproks = LagrangePol(eval_x,titik_x,titik_y)

print('the approximation value of x = {0} is y = {1:.5f}'.format(eval_x,y_aproks))

也許您想要一個SymPy解決方案?

from sympy import *

xi = [1, 2, 3, 5, 6]
yi = [10, 17, 8, 2, 4]
n = len(xi)
assert n == len(yi), "xi and yi need to be the same length"

x = Symbol('x', real=True)

lagrange_base = [prod([(x-xi[j])/(xi[i]-xi[j]) for j in range(n) if j != i ]) for i in range(n)]

lagrange = sum([yi[j] * lagrange_base[j] for j in range(n)])
#print(lagrange)
lagrange = simplify(lagrange)
print(lagrange)
print("for x=4: ", lagrange.subs(x, 4))

這打印:

-31*x**4/60 + 491*x**3/60 - 2651*x**2/60 + 5401*x/60 - 87/2
for x=4:  11/10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM