得到不完整的答案作为函数的输出

getting not-full answer as the output of the function

我为一个使用称为巴比伦函数的技术实现 sqrt 函数的函数编写了这段代码。 它通过使用以下公式重复执行计算来逼近数字 n 的平方根:

nextGuess = (lastGuess + (n / lastGuess)) / 2

当nextGuess和lastGuess非常接近时,nextGuess是近似的平方根。 初始猜测可以是任何正值(例如 1)。这个值将是 lastGuess 的起始值。 如果 nextGuess 和 lastGuess 之间的差异小于一个非常小的数,比如 0.0001,那么 nextGuess 就是 n 的近似平方根。 如果不是,则 nextGuess 变为 lastGuess 并且近似过程继续。

def babyl(n):
    lastGuess=1.0
    while True:
        nextGuess=float(lastGuess+float(n/lastGuess))/2.0
        if abs(lastGuess-nextGuess)<0.0001:
            return nextGuess
        else:
            lastGuess=nextGuess
            nextGuess=float(lastGuess+float(n/lastGuess))/2.0
            if abs(lastGuess-nextGuess)<0.0001:
                return nextGuess

函数的输出是:

>>> babyl(9)
3.000000001396984
>>> babyl(16)
4.000000000000051
>>> babyl(81)
9.000000000007091
>>> 

如您所见,在点之后很久。

我想写一个用户输入正整数的测试程序 函数 return 大约是。平方值。

所以我编码了:

n=input("Please sir, enter a positive integer number and you'll get the approximated sqrt:")
print babyl(n)

答案很简短:

>>> 
Please sir, enter a positive integer number and you'll get the approximated sqrt:16
4.0
>>> ================================ RESTART ================================
>>> 
Please sir, enter a positive integer number and you'll get the approximated sqrt:4
2.0
>>> ================================ RESTART ================================
>>> 
Please sir, enter a positive integer number and you'll get the approximated sqrt:9
3.0000000014
>>> 

谁能告诉我函数和测试有什么区别?

控制台使用repr( )显示结果。 print 使用 str( )

>>> import math; f = math.sqrt(10)
>>> str(f)
'3.16227766017'
>>> repr(f)
'3.1622776601683795'
>>> print f
3.16227766017

奇怪的是你错过了输出的精度。您的 epsilon 是 0.0001,短了几位数字,这将导致精度非常差,至少对于这些小数字而言。为什么要担心输出呢?

printfloat 对象上调用 __str__()。只需在 Python 提示符下调用该函数并让 Python 显示结果调用 __repr__()__str__() 由于浮点精度问题而使用的精度略低:许多小数值无法精确存储,这会导致涉及它们的计算不准确。