Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Decimal part of a large float

Tags:

python

I'm trying to get the decimal part of (pow(10, i) - 1)/23 for 0 < i < 50. I have tried

(pow(10, i) - 1)/23 % 1

in Python 3 but I get 0.0 for all values of i greater than 17.

How can I extract the decimal part of a large integer in Python?

like image 305
Randomblue Avatar asked Dec 01 '25 05:12

Randomblue


1 Answers

To preserve precision, I'd probably use the fractions module:

>>> from fractions import Fraction
>>> Fraction(10)
Fraction(10, 1)
>>> Fraction(10)**50
Fraction(100000000000000000000000000000000000000000000000000, 1)
>>> Fraction(10)**50-1
Fraction(99999999999999999999999999999999999999999999999999, 1)
>>> (Fraction(10)**50-1)/23
Fraction(99999999999999999999999999999999999999999999999999, 23)
>>> ((Fraction(10)**50-1)/23) % 1
Fraction(5, 23)
>>> float(((Fraction(10)**50-1)/23) % 1)
0.21739130434782608

although using the decimal module would be another option.

update: wait, on second thought, the answer here is always going to be ((10^n-1) % 23)/23, so the above is significant overkill (although it does scale up better to more complex problems). We can even take advantage of the three-argument pow call:

>>> pow(10, 50, 23)
6
>>> pow(10, 50, 23) - 1
5
>>> (pow(10, 50, 23) - 1) % 23 # handle possible wraparound
5
>>> ((pow(10, 50, 23) - 1) % 23) / 23.0
0.21739130434782608
like image 62
DSM Avatar answered Dec 03 '25 20:12

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!