How to stop SymPy from outputting a float representation of fraction in the output of srepr()

Viewed 24

The problem I am having is that when I have a fraction as an exponent in my sympy function, srepr evaluates that fraction and returns a float. I would like for the fraction to remain in the expression tree output instead of being evaluated and returned as a float.

Example: Function = (x**3 - 7)^(3/7)

srepr(Function)

Output: "Pow(Add(Pow(Symbol('x'), Integer(3)), Integer(-7)), Float('0.42857142857142855', precision=53))"

Doing this process backwards, the function above can be represented by

Pow(Add(Pow(x,3),-7),Rational(3, 7))

where the fraction (3/7) is represented by Rational. However as seen above, the output of srepr of this same function will not contain "Rational" to represent the fraction. O.O

The same thing happens when I evaluate an expression by a SymPy function such as "Integral", the fraction gets converted to a float instead of remaining as a fraction. The reason why I need the fraction is because I am doing manual integration so manipulation of the fraction is important for seeing how the process is carried out.

Any help will be greatly appreciated

1 Answers

Roughly speaking, when you write (x**3 - 7)^(3/7), Python will look at the command and perform the division 3/7=0.428571428571. Later on, Python will see the symbolic object x and SymPy will "kick in" with its operators, resulting in a symbolic expression.

In these occasions you have a couple of options:

from sympy import *
var("x")

# Option 1: explicitly write the division as a rational
expr = (x**3 - 7)**Rational(3, 7)

# Options 2: sympify (ie, convert) one of the numbers to a SymPy object.
# Here, I'm going to convert the Python int 2 to a SymPy's Integer.
# So when Python interpret the following command, it will ask SymPy to
# perform the division.
expr = (x**3 - 7)**(S(2) / 3)
Related