如何在Python中使方程达到最大秩

s3fp2yjn  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(122)

我试图做一个拉格朗日函数,但当我打印它不显示它会如何,如果乘法发生。我的代码如下:

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)

在输出中,我得到以下内容:

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)

我更喜欢这样的东西

3            2
3.395e-06 x - 0.001528 x + 1.976 x + 25
bpzcxfmw

bpzcxfmw1#

使用simplify函数

...
from sympy import simplify
...
...
print(Lagrange(x1, y1))
poly=simplify(lagrange(x1,y1))
print(poly)
siv3szwd

siv3szwd2#

看起来你想要的是得到扁平化的表达式(没有括号),可能是浮点数的低精度表示。这是通过扩展和求值来完成的:

>>> from sympy import expand_mul  # expand will do the same but is less specific
>>> expand_mul(poly)
11*x**3/3240000 - 11*x**2/7200 + 3557*x/1800 + 25
>>> _.n(4)
3.395e-6*x**3 - 0.001528*x**2 + 1.976*x + 25.0

相关问题