Maximum recursion depth error in Sympy when using non commutative symbols

780 views Asked by At

I have some big expressions which have their symbols with the attribute is_commutative=False.

Here is an example:

import sympy
from sympy import pi, sin, cos, exp
sympy.var('L, xPL, cosa, i, j, r2, sina, t, x', commutative=False)
sin.is_commutative = False
cos.is_commutative = False
exp.is_commutative = False


f = L*(r2 + sina*x)**(-1)*cosa*x*exp(10000.0*x*xPL*(2*i + 1 + i**2)**(-1)/L**2 \
    - 5000.0*xPL**2*(2*i + 1 + i**2)**(-1)/L**2 - 5000.0*x**2*(2*i + 1 \
    + i**2)**(-1)/L**2)*cos(pi*j*t - j*t**2/2 + pi*t - t**2/2) \
    - (r2 + sina*x)**(-1)*cosa*x**2*exp(10000.0*x*xPL*(2*i + 1 \
    + i**2)**(-1)/L**2 - 5000.0*xPL**2*(2*i + 1 + i**2)**(-1)/L**2 \
    - 5000.0*x**2*(2*i + 1 + i**2)**(-1)/L**2)*cos(pi*j*t - j*t**2/2 + pi*t - t**2/2)

If I try to do f.simplify() it raises an error:

RuntimeError: maximum recursion depth exceeded.

I already tried the "gotcha" sys.setrecursionlimit, but in this case it doesn't help.

What helps is to set commutative=True in sympy.var. (Without need to set it True to sin, cos and exp)

Since these expressions come from a previous process, I have the following workaroud:

def get_new_f(f):
    sin.is_commutative = True
    cos.is_commutative = True
    exp.is_commutative = True
    str_f = str(f)
    for s in f.free_symbols:
        sympy.var(str(x))
    return eval(str_f)r

Then get_new_f(f).simplify() works!

Is there another way to overcome this error?

1

There are 1 answers

2
asmeurer On

With such a small expression, a recursion error like this most likely indicates a bug in SymPy. You should report this as a bug at the SymPy issue tracker.