Search code examples
pythonmathsympyfractionsintegral

How to keep fractions in your equation output


I've been using Python to calculate math equations. For example:

from sympy import Symbol, Derivative, Integral
x = Symbol('x')
d = Symbol('d')
Integral(8*x**(6/5)-7*x**(3/2),x).doit()

Which results in the output:

3.63636363636364*x**2.2 - 2.8*x**2.5

Is there a way to show this answer as fractions as opposed to decimals? I would like to see the output as:

(40/11)*x**(11/5)-(14/5)*x**(5/2)+C

Solution

  • SymPy has Rational class for rational numbers.

    from sympy import *
    # other stuff 
    integrate(8*x**Rational(6, 5) - 7*x**Rational(3, 2),x)
    

    No need for Integral().doit() unless you actually want to print out the un-evaluated form.

    Other versions:

    integrate(8*x**Rational('6/5') - 7*x**Rational('3/2'),x)
    

    (rational number can be parsed from a string);

    integrate(8*x**(S.One*6/5) - 7*x**(S.One*3/2),x)
    

    (beginning the computation with the SymPy object for "1" turns it into SymPy object manipulation, avoiding plain Python division, which would give a float)