ufunc位运算异或的TypeError

51 投票
2 回答
171299 浏览
提问于 2025-04-18 00:23

在我的程序中,我正在追踪一个粒子的路径,但我遇到了以下错误:

Traceback (most recent call last):
  File "C:\Users\Felix\Google Drive\Research\particles.py", line 154, in <module>
    bfield += b_X(r_p(r,pos[2]))*(r_p(r,pos[2])/r)   
   *((r-r_p(r,pos[2]))**2+pos[2]**2)^(-1/2)*np.array
   ([(1-r_p(r,pos[2])/r)*pos[0],(1-r_p(r,pos[2])/r)*pos[1],pos[2]])

TypeError: ufunc 'bitwise_xor' not supported for the input types, 
and the inputs could not be safely coerced to any supported types 
according to the casting rule ''safe''

我找不到问题出在哪里。我没有使用过xor这个东西(不过我想它可能隐藏在一个if/else的语句里)。

2 个回答

8

在Python中,使用**来表示一个数的幂,而不是用^。

100

在出错的那一行,你用了一个 ^,但你其实应该用 ** 来表示一个数的幂运算。Python会把 ^ 解释成异或运算:

bfield += b_X(r_p(r,pos[2]))*(r_p(r,pos[2])/r)*((r-r_p(r,pos[2]))**2+
        pos[2]**2)^(-1/2)*np.array([(1-r_p(r,pos[2])/r)*pos[0],
        (1-r_p(r,pos[2])/r)*pos[1],pos[2]])

详情请见:

http://docs.python.org/2/reference/expressions.html#binary-bitwise-operations

撰写回答