Salem Derisavi
Salem Derisavi

Reputation: 137

sympy match has difficulty with modulo

Following this StackOverflow question, and a fix provided by @smichr, I tried the following:

>>> from sympy import *
>>> k,m,n = symbols("k m n", integer=True)
>>> (3*k+4)%2 - k%2
0                   # it works with the fix above. Thank you!
>>> p = Wild('p')
>>> q = Wild('q')
>>> e = (2*k+7)%5 + 7*k+7
>>> e
7*k + Mod(2*k + 2, 5) + 7
>>> e.match(p%5+p)
>>> e.match((p+5*q)%5+p)
>>> e.match(p%5+p+5*q)
{q_: k + 1, p_: 2*k + 2}

I expected the first or second e.match to work for me ({p:7*k+7} for first one and {p:7*k+7,q:-k} for second one), but it didn't. Is this a bug? If yes, is there a fix/workaround?

Upvotes: 1

Views: 114

Answers (1)

asmeurer
asmeurer

Reputation: 91660

(Copying the same thing I wrote on the SymPy issue)

match has very limited mathematical knowledge. It doesn't know that the 2*k in the Mod can be replaced with 7*k.

I'm not sure if this would be easy to fix. match is already pretty complicated with the limited mathematical matching it does. A better design would likely be needed to solve problems like this. Actually this strikes me as the sort of problem that you would need an SMT solver to solve, but maybe there are simpler algorithms that could do it.

Sorry this doesn't give a direct answer on how to solve the problem.

Upvotes: 1

Related Questions