【问题标题】:How to read polyfit function in python?如何在 python 中读取 polyfit 函数?
【发布时间】:2018-11-24 08:37:18
【问题描述】:

我想通过给出值来生成一个多项式方程并得到一个方程。然而,当我用给定的 x 值控制它时,我从方程中得到不同的值,这是我的代码和输出:

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])

x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)

它给了我这个等式:-0.001416*x^2 + 0.1504*x + 1.72

输出

x   expected(y) returned(y)

1     1         1.868984
2     4         2.015136
3     1         2.158456
9     3         2.9589040000000004

是我错了还是我读错了?

【问题讨论】:

  • 一个流行的 Python 绘图库是Matplotlib

标签: python python-3.x numpy


【解决方案1】:

您似乎误解了多项式拟合的概念。当您调用polyfit(x, y, n) 时,它会为您提供最适合点集 (x, y) 的 n 次(或更小)次多项式。因此,通过使用n = 2 调用 polyfit,它会返回适合您给出的点的最佳二次多项式。该多项式只是您的集合的近似值,因此预计返回值与预期值不同,而且由于二次多项式无法很好地表示它们而变得更糟。

以下代码直观地演示了这是如何实现的。改变你的观点,polyfit() 函数的n 值,看看你是否能更好地掌握这个概念:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])

x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)

x_fit = np.linspace(-100, 100, 1000)
y_fit = [f(_x) for _x in x_fit]

plt.plot(x, y)
plt.plot(x_fit, y_fit)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2019-10-04
    • 2020-04-10
    • 2019-03-18
    • 1970-01-01
    • 2018-10-31
    • 2019-12-26
    相关资源
    最近更新 更多