短版,Python 正在四舍五入输出:)
import math as M
frct = M.sqrt(2)
for i in range(7):
frct = 1 / (frct - int(frct))
print 'Attempt %d: %.20f' % (i, frct)
长版本,浮点不存储真实(没有双关语)值,它们存储指数和尾数。有关更多信息,请参阅此维基百科页面:http ://en.wikipedia.org/wiki/Floating_point
基本上,浮点数的存储方式如下:
Significant digits × base^exponent
如果您想要 Python 中更精确的版本,请尝试使用 decimal 模块:
import decimal
context = decimal.Context(prec=100)
frct = context.sqrt(decimal.Decimal(2))
print 'Original square root:', frct
for i in range(7):
frct = context.divide(1, frct - int(frct))
print 'Attempt %d: %s' % (i, frct)
输出:
Original square root: 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573
Attempt 0: 2.414213562373095048801688724266222622763067167798368627068136427003657772608039155697953022512189319
Attempt 1: 2.414213562373095048801688723683379910288448158038030882339615025168647691299718507620657724911891709
Attempt 2: 2.414213562373095048801688727180436185136162216600057354932063779738350752352175486771948426117071942
Attempt 3: 2.414213562373095048801688706780941248524496874988236407630784335182989956231878308913506955872772859
Attempt 4: 2.414213562373095048801688825680854593346774866097140494471009059332623720827093783193465943198777227
Attempt 5: 2.414213562373095048801688132680869461024772261055702548455940065126184103929661474210576202848416747
Attempt 6: 2.414213562373095048801692171780866910134509900201052604731129303452089934643341550673727041448985316