开发者

Numpy Modular arithmetic

开发者 https://www.devze.com 2023-01-16 02:34 出处:网络
How can I define开发者_StackOverflow社区 in numpy a matrix that uses operations modulo 2? For example:

How can I define开发者_StackOverflow社区 in numpy a matrix that uses operations modulo 2?

For example:

0 0       1 0       1 0
1 1   +   0 1   =   1 0

Thanks!


This operation is called "xor".

>>> import numpy
>>> x = numpy.array([[0,0],[1,1]])
>>> y = numpy.array([[1,0],[0,1]])
>>> x ^ y
array([[1, 0],
       [1, 0]])

BTW, (element-wise) multiplication modulo 2 can be done with "and".

>>> x & y
array([[0, 0],
       [0, 1]])


You could subclass numpy.ndarray and override the __add__ method, but I think it would be far simpler to just be explicit. For example:

import numpy as np
x = np.array([[0,0],[1,1]])
y = np.array([[1,0],[0,1]])

print (x + y) % 2

Which yields:

array([[1, 0],
       [1, 0]])
0

精彩评论

暂无评论...
验证码 换一张
取 消