Search code examples
pythonsympysymbolic-computation

SymPy, how to perform exact symbolic representation (Rational Issue)?


So I'm planning to write a web application about math, and I need to convert user input to a SymPy expression without modifying it (Simplification), eg. so I'd like to cancel this behaviour like in this example.

>>> srepr(Rational(2,4)) #this is the problem
'Rational(1, 2)'

>>> srepr(Rational(2,4,evaluate=False)) #doesn't work
Traceback...

But I've managed to do it in other types of representations.

>>> srepr(Pow(x,(Mul(e,e,evaluate=False)),evaluate=False)) #nice
"Pow(Symbol('x'), Mul(Symbol('e'), Symbol('e')))"

>>> srepr(sqrt(Integer(8))) #not what I want
'Mul(Integer(2), Pow(Integer(2), Rational(1, 2)))'

>>> srepr(Pow(Integer(8),Rational(1,2),evaluate=False)) #this is the way
'Pow(Integer(8), Rational(1, 2))'

>>> from sympy import E
>>> log(E,evaluate=False)
log(E)

Also isn't there a way to tell SymPy that all representations shouldn't be evaluated?


Solution

  • Something like this, perhaps?

    >>> S('2/4',evaluate=False)
    2/4
    >>> srepr(_)
    'Mul(Integer(2), Pow(Integer(4), Integer(-1)))'