python不确定性包中的ZeroDivisionError

时间:2014-09-05 11:27:35

标签: python arrays math numpy

我正在尝试对具有不确定性的阵列进行一些数学运算。数组中有一些值,它们具有ZeroDivisionError。我想跳过该错误并继续对数组进行数学运算 代码示例如下,

import numpy as np
from uncertainties import ufloat
from uncertainties.umath import *
from uncertainties import unumpy

datafilename = 'exp_data_ratio.txt'
g = np.genfromtxt(datafilename, delimiter = ',')
Eb = g[:,0]
R0 = g[:,1]
Rexp = g[:,2]
Rerr = g[:,3] # error in Rexp
R = unumpy.uarray(Rexp, Rerr) # array (R +/- dR)

def div_check(a,b):
    if b.any() != 0:
        value = a/b
    else:
        value = float('Inf')

x = 2*(R0-R)
y = (R+2)*(R0-1)
factor = div_check(x,y)
Ep = Eb*factor
print Ep

我收到此错误消息,

>>>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
    execfile(filename, namespace)
  File "/home/chintan/Desktop/e-spiralling/uncertainity_test.py", line 33, in <module>
    factor = div_check(x,y)
  File "/home/chintan/Desktop/e-spiralling/uncertainity_test.py", line 25, in div_check
    value = a/b
  File "/usr/lib/python2.7/site-packages/uncertainties/__init__.py", line 880, in f_with_affine_output
    f_nominal_value = f(*args_values, **kwargs)
ZeroDivisionError: float division by zero

2 个答案:

答案 0 :(得分:2)

如果iterable中的任何元素为true,则

any()返回true。您可以使用if b.all():替换该行。

答案 1 :(得分:2)

使用where函数怎么样?

import numpy as np
b = np.zeros(3)
a = np.ones(3)
c = np.zeros(3)
b[0] = 2; b[2] = 3
ind = np.where(b != 0)
c[ind] = a[ind]/b[ind]