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

时间:2016-02-05 21:32:44

标签: python function while-loop output floating

我为一个使用称为Babylonian函数的技术实现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
>>> 

你看到点之后很久。

我想编写一个测试程序,用户输入一个正整数 功能返回大约。 sqrt值。

所以我编码:

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
>>> 

有人可以告诉我功能和测试之间有什么区别吗?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

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