Python求图的给定坐标方程

2024-04-26 00:32:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图建立一个程序,找到(粗略地)一个图的方程,给定一组点在图上的坐标。假设给定的坐标代表整个图(即:行为在给定域外不会改变)。在

我使用下面的简单函数来执行此操作:

#x and y are arrays of the x coordinates and corrosponding y coordinates
def get_equation(x,y):
    degree = 2
    coefs, res, _, _, _ = np.polyfit(x,y,degree, full = True)
    ffit = np.poly1d(coefs)
    print (ffit)
    return ffit

对于基本方程图(如x^2)上的坐标,这种方法相当有效,但对于更复杂的图形(如下图)则根本不起作用。在

enter image description here

如何找到更复杂的图的方程,比如上面给出的图的坐标?在

另外,有没有可能计算出图形的度数,或者总是需要手动输入?在


Tags: andof函数程序图形np代表are
2条回答

如果行为在给定的域外没有改变,请查看样条曲线并将其与域相匹配。这可以用scipy.插值. 在

这里有一个例子

 from matplotlib.pyplot import subplots
from numpy import linspace, random, sin, cos
from scipy import interpolate

x = linspace(0, 10)

y = sin(x * .5) + cos (x * 2)  + random.randn(x.size) * 1e-1
# fit spline
spl = interpolate.InterpolatedUnivariateSpline(x, y)
fitx = linspace(0, x.max(), 100)

fig, ax = subplots()
ax.scatter(x, y)

ax.plot(fitx, spl(fitx))
fig.show()

你需要改变多项式的度数。例如,我创建了一个五阶多项式。在

import numpy as np
import matplotlib.pyplot as plt
def SomePoly(k):
    a = [9, 1.5, -12.5, -2.5, 3.5, 1]
    return sum([a[p]*k**p for p in range(len(a))])
x = np.arange(-3,2, 0.1)
y = SomePoly(x)
plt.plot(x, y)

现在查看每个学位的结果:

^{pr2}$

结果:

2 [947.22023682]
4 [683.734662]
5 [8.70566837e-27]

相关问题 更多 >