Python: decimal of a large float

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

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

in Python 3, but I get 0.0for all values igreater than 17.

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

+3
source share
3 answers

To maintain accuracy, I would 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 decimal would be another option.

update: wait, on the other hand, the answer will always be here ((10^n-1) % 23)/23, so the above is a significant excess (although it is better suited for more complex problems). We can even take advantage of three pow call arguments:

>>> 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
+8

, , -

N = 10**i - 1
remainder = N % 23
print remainder / 23.0

, .

pow, , , .

((pow(10, i, 23) + 22) % 23) / 23.0
+1

: " float Python? , ...: -)

Python 2.7 i=20 ( 23.0, ), 4.347826086956522e+18. 16 10 ^ 18. , " " ( für i=20, , , , ).

, i.

0

All Articles