当curve_fit抛出TypeError时,如何避免python停止

时间:2012-12-11 08:34:24

标签: python exception scipy curve-fitting

我正在使用python对我的代码进行数据分析。我目前正在尝试调试一些东西,所以我将一些可能无效的数据放入我的python代码中。使用curve_fit的一行会给我TypeError

TypeError: array cannot be safely cast to required type
Traceback (most recent call last):
  File "makeStuffUnHR.py", line 405, in <module>
    FT = plotFT(FT,A)
  File "makeStuffUnHR.py", line 325, in plotFT
    line,pars = fitFTsurfaceTension(FTRange2,fty,a)
  File "/home/yotam/Applications/Process/dataHandler.py", line 75, in fitFTsurfaceTension
    popt, pcov = curve_fit(FTfuncSurface,x,log(y))
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 426, in curve_fit
    res = leastsq(func, p0, args=args, full_output=1, **kw)
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 283, in leastsq
    gtol, maxfev, epsfcn, factor, diag)
minpack.error: Result from function call is not a proper array of floats.

我试图在没有运气的情况下捕获“TypeError”异常

如何让python继续运行代码?

修改

这是我的尝试,期待部分:

try:
    popt, pcov = curve_fit(FTfuncSurface,x,log(y))
except TypeError:
    popt = [0,0]

1 个答案:

答案 0 :(得分:0)

使用try / except块来捕获TypeError例外。

示例代码:

try:
   a = (1,2,3) #Some code
except IndexError:
   pass