How to keep fractions in your equation output
Asked Answered
L

3

14

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
Lakieshalakin answered 12/8, 2017 at 13:49 Comment(0)
W
16

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)

Whitewood answered 12/8, 2017 at 14:8 Comment(2)
Any idea on how we would use Rational on non-division problems such as integrate((x+1)*math.e**((7*x**2)+(14*x)))?Lakieshalakin
@Lakieshalakin 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.Whitewood
H
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()
Headon answered 12/8, 2017 at 13:58 Comment(0)
E
6

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()
Edom answered 12/8, 2017 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.