If I divide 100/40 in python how can I get value of 5/2 without python performing true division or decimal division Eg:
- If I divide 100 by 20 i need value of 5/1 in python not simply 5 similarly for 100 by 40 i need to get a value of 5/2 not 2.5 and for 100/60 value 5/3 how can i get that in python.
CodePudding user response:
You can use the fractions
module
In [1]: from fractions import Fraction
In [2]: Fraction(100, 40)
Out[2]: Fraction(5, 2)
or the sympy
(Symbolic Python) module
In [3]: from sympy import Rational
In [4]: Rational(100, 40)
Out[4]: 5/2
The sympy
module is much more complex and opens to you a world of symbolic computations, the fractions
module loads immediately and does JUST what you asked for.
The choice is yours…
CodePudding user response:
You can use the fractions module:
import fractions
f = fractions.Fraction(100 / 40)
print(f'{f.numerator}/{f.denominator}')
Result:
5/2