Search code examples
pythonsympymodular-arithmetic

Modulo computations in Sympy fail


I have a computation in Sympy, which I want to be modulo 2. However, if I just write

from sympy.abc import x
(((x + 1) % 2) + 1) % 2

Then this has the output Mod(Mod(x + 1, 2) + 1, 2), i.e. the two +1 do not vanish. Even calling .simplify() does not have the desired effect.

Another post (Modulo 2 arithmetics in SymPy) suggested sympy.trunc. But this function does not work if the expression is integer. I even tried sympy.trunc(sympy.sympify(1),2), but this still raised an Error.

So how do I get a modulo function that works on integers and all coefficients?

PS: I am aware that this is a basic question, and I was confused, that I could not find an answer.


Solution

  • A better way to handle this is to use Poly with the modulus flag:

    >>> Poly(x + 1, x, modulus=2) + Poly(1, x, modulus=2)
    Poly(x, x, modulus=2)