0

我试图了解下面的 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
4

2 回答 2

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 中更精确的版本,请尝试使用 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
于 2013-01-30T23:22:17.423 回答
3

print frct显示str(frct)哪个显示的有效数字数量少于准确复制数字所需的数量。替换print frctprint repr(frct),您会发现前五次数字不一样,它们变化得足够慢(起初),以使其四舍五入的表示保持不变:

2.4142135623730945
2.4142135623730985
2.414213562373075
2.414213562373212
2.4142135623724124
2.414213562377074
2.414213562349904
于 2013-01-30T23:17:18.333 回答