我有一段由于各种原因可能会失败的数字代码,我想用 numpy.NAN 替换输出值,这样事情就会继续发展。我试图将对 brentq 的调用包装在 try:except: 语句中,但它仍然使我的代码因同一个异常而崩溃。
def someotherfunction(stuff):
self.energy2ph = lambda e: self.brentq_fails_to_NAN(ph2offset_energy, 0., max_ph, args=(e,))
def brentq_fails_to_NAN(self, *args):
''' this simply calls scipy.optimize.brentq with the exact same arguments,
but in the case of an error it returns numpy.NAN instead of throwing an exception '''
try:
return scipy.optimize.brentq(*args)
except:
print 'returning numpy.NAN instead of throwing an exception for energy2ph'
return numpy.NAN
我得到一个回溯,但有一个异常可以追溯到我的 try 语句。我的理解是应该在那种情况下运行 except: 语句下的代码
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mass/calibration/energy_calibration.pyc in name2ph(self, name)
257
258 def brentq_fails_to_NAN(self, *args):
--> 259 try:
260 return scipy.optimize.brentq(*args)
261 except:
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mass/calibration/energy_calibration.pyc in <lambda>(e)
252 max_ph = 1.3*self._ph[-1]
253 ph2offset_energy = lambda ph, eoffset: self.ph2energy(ph)-eoffset
--> 254 # self.energy2ph = lambda e: scipy.optimize.brentq(ph2offset_energy, 0., max_ph, args=(e,))
255 self.energy2ph = lambda e: self.brentq_fails_to_NAN(ph2offset_energy, 0., max_ph, args=(e,))
256
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/zeros.pyc in brentq(f, a, b, args, xtol, rtol, maxiter, full_output, disp)
387 if type(args) != type(()) :
388 args = (args,)
--> 389 r = _zeros._brentq(f,a,b,xtol,maxiter,args,full_output,disp)
390 return results_c(full_output, r)
391
ValueError: f(a) and f(b) must have different signs