如何在没有numpy的情况下使用numpy多项式表达式?

问题描述 投票:0回答:1

为了跟进上一个问题,我想在没有numpy的python环境中提取多项式来计算某些值的结果。

代码:

import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import Polynomial
x = [430, 518, 471, 581, 330, 560, 387, 280, 231, 196, 168, 148, 136, 124, 112, 104, 101, 93, 88, 84, 80, 76]
y = [13, 10.5, 11.5, 10, 16.9, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]

plt.figure(figsize=(12,6))
plt.plot(x, y, 'o')
polynomial = Polynomial.fit(x, y, deg=7)
x1 = np.arange(76, 570, 1)
y1 = [polynomial(i) for i in x1]
plt.plot(x1, y1, '-')
print("polynomial result :")
print(polynomial)
print("-------------------")

# test single value of x
x2 = 330
y2_direct = 16.94343988 - 11.3117263*x2 + 17.65987276*x2**2 - 31.01304843*x2**3 - 21.01641368*x2**4 + 46.31228129*x2**5 + 36.3575357*x2**6 - 44.05000699*x2**7
y2_poly = polynomial(x2)
print("y2_direct = ", y2_direct)
print("y2_poly = ", y2_poly)

plt.legend('data deg7'.split())
plt.show()

我明白了:

enter image description here

enter image description here

为什么y2_direct和y2_poly这2个值不同?

python numpy
1个回答
0
投票

打印到控制台的多项式的字符串表示形式不完整。如果您显示它(例如在 Colab 上),则表明在评估多项式之前您的数据需要移动并缩放数据:

x2 = 330
x2 = -1.3009901 + 0.0039694*x2  # shift and scale data

16.94343988 - 11.3117263*x2 + 17.65987276*x2**2 - 31.01304843*x2**3 - 21.01641368*x2**4 + 46.31228129*x2**5 + 36.3575357*x2**6 - 44.05000699*x2**7
# 16.84401140712287
© www.soinside.com 2019 - 2024. All rights reserved.