Search code examples
pythonnumpymathmodular

Numpy Modular arithmetic


How can I define in numpy a matrix that uses operations modulo 2?

For example:

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

Thanks!


Solution

  • 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]])