用任意函数拟合数据,并在达到一定值时进行检查

2024-07-02 13:38:58 发布

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

就像标题说的。我想符合这些要点。找到一个函数并检查我的函数将在哪个x处达到100。你知道吗

    import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit



points = np.array([(3, 0), (7, 55), (14, 88)])
x = points[:,0]
y = points[:,1]
def func(x, p1,p2):
  return p1*np.log(x)+p2

popt, pcov = curve_fit(func, x, y,p0=(1.0,10.2))
print popt
p1 = popt[0]
p2 = popt[1]

curvex=np.linspace(15,85,1000)
fit = func(curvex, p1, p2)
plt.plot(x, y, 'yo', label='data')



plt.plot(curvex,fit,'r', linewidth=5)

plt.plot(x,y,'x',label = 'Xsaved')

plt.show()

enter image description here

  1. 如何使函数通过点?(如果工作量过大,则不需要)

  2. 如何得到y=100的x值?

谢谢!你知道吗


Tags: 函数importplotasnppltlabelpoints
3条回答
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.interpolate import interp1d


points = np.array([(3, 0), (7, 55), (14, 88)])
x = points[:,0]
y = points[:,1]
def func(x, p1,p2):
  return p1*np.log(x)+p2

popt, pcov = curve_fit(func, x, y,p0=(1.0,10.2))
print popt
p1 = popt[0]
p2 = popt[1]

curvex=np.linspace(15,85,1000)
fit = func(curvex, p1, p2)
plt.plot(x, y, 'yo', label='data')

f = interp1d(fit, curvex, kind = 'cubic')
print f(100)
plt.plot(curvex,fit,'r', linewidth=1)

plt.plot(x,y,'x',label = 'Xsaved')

plt.show()

这回答了我的问题。函数在x=16.54处穿过y=100。你知道吗

有两个Y值为零的数据点。在去掉X值最小的单个数据点(散点图上最左边的点)后,我可以很容易地将剩余的数据拟合到方程“y=a*ln(X+b)”,这似乎有点合理,因为你是在对散点图右侧进行外推。你知道吗

plot2

要找到此公式中Y=100的X值:

100=a*ln(x+b)

我重新安排为:

100/a=ln(x+b)

取每边的自然指数:

exp(100/a)=x+b

从两边减去b得到:

经验值(100/a)-b=x

使用参数a和b的拟合值:

a=3.5059370092556854E+01

b=-2.00572996456858785E+00

既然b是负数,这就给了我:

实验(100/3.5059370092556854E+01)+2.00572996458785E+00=x

我的计算器将其解为x在100时的近似值:

19.3334=x

可以在多项式搜索中添加次。尝试4而不是3例如,它不会超过100

import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import Polynomial as P

points = np.array([(0, 0), (3, 0), (7, 55), (14, 88)])
x = points[:,0]
y = points[:,1]

y_fit = P.fit(x, y, 4)


x_new = np.linspace(x[0], x[-1], 50)

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

enter image description here

如果你真的想试着用四阶近似计算它何时达到100:

import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import Polynomial as P

points = np.array([(0, 0), (3, 0), (7, 55), (14, 88)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

y_fit = P.fit(x, y, 4)
x_new = np.linspace(0, 20, 100)

plt.plot(x,y,'o', x_new, y_fit(x_new))
plt.axhline(100)
plt.show()

enter image description here

但是没有什么能保证这一趋势的真实性,因为它也可以用任何其他次序或任何其他函数来近似

相关问题 更多 >