Python - 获取给定坐标的图形方程 [英] Python - Get equation of graph given coordinates

查看:53
本文介绍了Python - 获取给定坐标的图形方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个程序,在给定图形上一堆点的坐标的情况下,该程序可以(粗略地)找到图形的方程.假设给定的坐标代表整个图(即:行为在给定域之外不会改变).

I am attempting to build a program that finds (roughly) the equation of a graph given the coordinates of a bunch of points on the graph. The assumption is made that the coordinates given represent the entirety of the graph (ie: the behavior does not change outside the given domain).

我使用下面的简单函数来做到这一点:

I use the simple function below to do this:

#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 等基本方程的图形上的坐标相当有效,但对于更复杂的图形(如下图)则根本不起作用.

This works reasonably well for the coordinates on the graphs of basic equations such as x^2, but does not work at all for more complicated graphs such as the graph below.

如何根据图形上的坐标找到更复杂图形的方程,例如上面的图形?

How do I find the equation for more complex graphs like the one above given the coordinates on the graph?

另外,是否可以确定图形的度数是多少,还是必须始终手动输入?

Also, is it possible to figure out what the degree of the graph is, or does that always have to be entered manually?

推荐答案

如果行为在给定域之外没有改变,请查看样条曲线并将其拟合到域中.这可以通过 scipy.interpolate 来完成.

If the behavior does not change outside the given domain, look into splines and fit those to the domain. This can be done with scipy.interpolate.

这是一个例子

 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()

这篇关于Python - 获取给定坐标的图形方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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