用指数函数拟合 python 图

fitting the python plot with exponential function

我正在尝试用指数函数拟合我的 python 图。我在这里附上了代码。非常感谢任何意见。

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

x=[0.21, 0.43, 0.50, 0.65, 0.86, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0]
y=[43, 33, 30, 24, 18, 16, 14, 13, 14, 13, 13]
yerr= [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
xerr=[0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01, 0.01,0.01,0.01]
plt.ylim (0,60)
plt.xlabel ('Thickness (d) [mm]')
plt.ylabel ('Counts')
def exponenial_func(x, a, b, c):
    return a*np.exp(-b*x)+c
popt, pcov = curve_fit(exponenial_func, x, y, p0=(1, 1e-6, 1))
yy = exponenial_func(x, *popt)

plt.plot(x,y,'o', x, yy)
#plt.errorbar(x,y,yerr=yerr,xerr=xerr, fmt= '.')
plt.show()

我总是收到一条错误消息:

Traceback (most recent call last):
  File "/home/manisha/Desktop/Moessbauer effect/countsvsd.py", line 16, in <module>
    yy = exponenial_func(x, *popt)
  File "/home/manisha/Desktop/Moessbauer effect/countsvsd.py", line 14, in exponenial_func
    return a*np.exp(-b*x)+c
TypeError: 'numpy.float64' object cannot be interpreted as an index

由于我是一名新程序员,我不知道这意味着什么。 请帮忙。

您的问题在于您尝试定义的方式 yy;您不能在 list x 上调用您的函数。相反,在 x 中的每个单独项目上调用它,例如,在这样的列表迭代中:

yy = [exponenial_func(i, *popt) for i in x]

那么,您代码中的其他所有内容都可以正常工作:

[编辑]:要推断指数函数中的零(根据您的评论),您可以这样做:

xx = x.copy()    
yy = [exponenial_func(i, *popt) for i in [0]+xx]
plt.plot(x,y,'o',[0]+xx,yy)

或者,要只查看值,请执行以下操作:

exponenial_func(0, *popt)

虽然@sacul 的答案有效,但它并没有告诉你发生了什么。

如果你有一个 list,你可以通过乘法将这个 list 的副本附加到它本身。

my_list = [1, 2]
print(my_list * 2) #[1, 2, 1, 2]

因此,当您尝试将 listfloat 相乘时,复制的行为将变得不确定,并抛出 Exception

print(my_list * 1.5) #TypeError: can't multiply sequence by non-int of type 'float'

尝试使用浮点对象这样做,将在评估时间之前被捕获并引发以下错误:

a = 1.5
print(my_list*a) #TypeError: 'numpy.float64' object cannot be interpreted as an integer

所以你的问题有多种解决方案。您可以将 list 中的各个项目一个一个地提供给函数,就像@sacul 提供的答案一样,或者将您的容器转换为一种类型,它会像您预期的那样产生数组行为:

def exponenial_func(x, a, b, c):
    if isinstance(x,list):
        x = np.array(x)
    return a*np.exp(-b*x)+c