我试图通过更改两个参数(e
和A
)来拟合曲线。通过分配n0=0.395
绘制目标曲线,但其实际值为0.0395
。因此,我希望通过更改e
和A
来获得相同的曲线。
import numpy as np
from scipy.optimize import curve_fit
def func(x,e,A):
return A*(e+x)**0.0395
strain = np.linspace(0,15,3000) # variable
e = 0.773
A = 386.5
n0 = 0.395
y = A*(e+strain)**n0 # target to minimize
popt, pcov = curve_fit(func, strain, y)
但是,我在运行代码后不断收到此警告:
RuntimeWarning: invalid value encountered in power
return A*(e+x)**0.0395
我想知道为什么会发生这种情况,以及如何改进代码?
答案 0 :(得分:1)
我找到了我不喜欢的解决方案,但是它确实消除了警告。我发现,奇怪的是,curve_fit()中的“ e”被设为负数。我在函数内部添加了“砖墙”以阻止此情况,但是这应该是不必要的。我的代码是:
import numpy as np
from scipy.optimize import curve_fit
def func(x,e,A):
if e < 0.0: # curve_fit() hits a "brick wall" if e is negative
return 1.0E10 # large value gives large error, the "brick wall"
return A*(e+x)**0.0395
strain = np.linspace(0,0.1,3) # variable
e = 0.773
A = 386.5
n0 = 0.395
y = A*(e+strain)**n0 # target to minimize
popt, pcov = curve_fit(func, strain, y)