如何从Numpy的polyfit导出方程式? [英] How to derive equation from Numpy's polyfit?

查看:69
本文介绍了如何从Numpy的polyfit导出方程式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出x和y值的数组,以下代码将为这些数据点计算回归曲线.

Given an array of x and y values, the following code will calculate a regression curve for these data points.

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

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

如何使用以上方法得出该曲线的实际方程式?

How can I use the above to derive the actual equation for this curve?

推荐答案

如果要显示方程式,可以使用sympy输出乳胶:

If you want to show the equation, you can use sympy to output latex:

from sympy import S, symbols, printing
from matplotlib import pyplot as plt
import numpy as np

x=np.linspace(0,1,100)
y=np.sin(2 * np.pi * x)

p = np.polyfit(x, y, 5)
f = np.poly1d(p)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

x = symbols("x")
poly = sum(S("{:6.2f}".format(v))*x**i for i, v in enumerate(p[::-1]))
eq_latex = printing.latex(poly)

plt.plot(x_new, y_new, label="${}$".format(eq_latex))
plt.legend(fontsize="small")
plt.show()

结果:

这篇关于如何从Numpy的polyfit导出方程式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆