11

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
d84_n1nj4
  • 1,712
  • 6
  • 23
  • 40

3 Answers3

14

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)

  • Any idea on how we would use Rational on non-division problems such as `integrate((x+1)*math.e**((7*x**2)+(14*x)))`? – d84_n1nj4 Aug 12 '17 at 18:21
  • 1
    @d84_n1nj4 It's `integrate((x+1)*exp(7*x**2 + 14*x), x)` - use the exponential function, not `e**` But if you really want to, there is `E` in SymPy: `integrate((x+1)*E**(7*x**2 + 14*x), x)` works too. The general thing is, plain Python constants are floating point numbers, which is not what you want. You want the corresponding SymPy objects, obtainable from SymPy directly. –  Aug 12 '17 at 18:44
7

you can work with the fractions module in order to have integral fractions:

from sympy import Symbol, Derivative, Integral
from fractions import Fraction
x = Symbol('x')
d = Symbol('d')
ii = Integral(8*x**Fraction(6,5)-7*x**Fraction(3,2),x).doit()
# 40*x**(11/5)/11 - 14*x**(5/2)/5

there is also the Rational class in sympy itself:

from sympy import Symbol, Derivative, Integral, Rational
x = Symbol('x')
d = Symbol('d')
ii = Integral(8*x**Rational(6,5)-7*x**Rational(3,2),x).doit()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
5

Use sympy's rational instead of 6/5. Python will immediately interpret 6/5 and return some floating point number (1.2 in this case).

from sympy import Symbol, Derivative, Integral, Rational
x = Symbol('x')
d = Symbol('d')
Integral(8*x**(Rational(6,5))-7*x**(Rational(3,2)),x).doit()
laolux
  • 1,445
  • 1
  • 17
  • 28