Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I keep decimal precision while using integer division in Python?

When I divide 2/3 I get 0.66666666, when I do 2//3 I get 0.

Is there any way to compute integer division while still keeping the decimal points?

Edit: looks like I may have confused a lot of you, my bad. So what my professor told me that since standard division(2/3) will only return 0.666666666666 up to 203 digits, it is not useful when I want to do computations that requires more than 203 digits after the decimal point. I am wondering if there is a way to do 2//3 (which will return 0) but somehow still get the .6666 in the end

like image 280
user3277633 Avatar asked Mar 21 '23 15:03

user3277633


1 Answers

For certain limited decimals, you can use Python's float .as_integer_ratio() method:

>>> 0.5.as_integer_ratio()
(1, 2)

For 2/3, which is not exactly representable in decimal, this starts to give less desirable results:

>>> (2/3).as_integer_ratio()
(6004799503160661, 9007199254740992)      # approximation of 2/3

For arbitrary precision of rational numbers, use fractions in the Python library:

>>> import fractions
>>> fractions.Fraction('2/3')
Fraction(2, 3)
>>> Frac=fractions.Fraction
>>> Frac('2/3') + Frac('1/3') + Frac('1/10')
Fraction(11, 10)
>>> Frac('2/3') + Frac('1/6') + Frac('1/10')
Fraction(14, 15)

Then if you want a more accurate representation of that in decimal, use the Decimal library to convert the integer numerator and denominator to an arbitrary precision decimal:

>>> f=Frac('2/3') + Frac('1/6') + Frac('1/10')
>>> f
Fraction(14, 15)
>>> f.numerator
14
>>> f.denominator
15
>>> import decimal
>>> decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator)
Decimal('0.9333333333333333333333333333')
like image 150
dawg Avatar answered Apr 19 '23 23:04

dawg