简体   繁体   中英

How to get a very long decimal digit by dividing a irrational number with another number in Python?

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?

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

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