关于连续分数的Python代码

时间:2013-01-30 23:11:26

标签: python

我正在尝试了解下面的python代码中发生了什么。我取2的平方根并将其小数除以1.执行此操作5次保持给出相同的值,但第6次和第7次我得到不同的值。

当输入值与前5次计算中的输入值相同时,为什么输出会在第6次发生变化?

import math as M
frct = M.sqrt(2)

# 1
frct = 1 / (frct - int(frct))
print frct # 2.41421356237

# 2
frct = 1 / (frct - int(frct))
print frct # 2.41421356237

# 3
frct = 1 / (frct - int(frct))
print frct # 2.41421356237

# 4
frct = 1 / (frct - int(frct))
print frct # 2.41421356237

# 5
frct = 1 / (frct - int(frct))
print frct # 2.41421356237

# 6
frct = 1 / (frct - int(frct))
print frct # 2.41421356238

# 7
frct = 1 / (frct - int(frct))
print frct # 2.41421356235

2 个答案:

答案 0 :(得分:9)

简短版本,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中使用更精确的版本,请尝试使用十进制模块:

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

答案 1 :(得分:3)

print frct显示str(frct),其显示的有效位数少于完全重现该数字所需的有效位数。将print frct替换为print repr(frct),您会看到前五次的数字不同,它们的变化足够慢(首先),因为它们的舍入表示保持不变:

2.4142135623730945
2.4142135623730985
2.414213562373075
2.414213562373212
2.4142135623724124
2.414213562377074
2.414213562349904