Reputation: 1
import math
from decimal import *
getcontext().prec = 10000
phi = str(Decimal(1+math.sqrt(5))/Decimal (2) )
print(phi)
print(len(phi))
#output >> phi - 1.6180339887498949025257388711906969547271728515625
#output >> len(phi) - 51
I wanted to get a 1000 digits long number but in Python, the limit seems to be at 51. So how can I do to get a very long digit in Python?
Upvotes: 0
Views: 88
Reputation: 70602
The math
module works with native binary floating-point arithmetic. So the crucial
1+math.sqrt(5)
part has nothing to do with the decimal precision you set. That part is done entirely in native binary floating-point.
To keep the output to reasonable length, let's try for 80 significant decimal digits instead. So
getcontext().prec = 80
and then
phi = str((1 + Decimal(5).sqrt()) / 2)
instead. Clear? Now the sqrt
method of a decimal object is being used instead, and that will respect the decimal precision you set. You can force 1
and 2
to Decimal
too but there's no real need to - they'll be converted automatically to Decimal
because their other operand is Decimal
. Output from the above:
1.6180339887498948482045868343656381177203091798057628621354486227052604628189024
81
Upvotes: 2