简体   繁体   中英

If I divide 100/40 in python how can I get value of 5/2 without python performing true division or decimal division

If I divide 100/40 in python how can I get value of 5/2 without python performing true division or decimal division Eg:

  1. 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.

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…

You can use the fractions module:

import fractions

f = fractions.Fraction(100 / 40)

print(f'{f.numerator}/{f.denominator}')

Result:

5/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM