简单的for循环功能

时间:2016-11-01 17:42:26

标签: python function for-loop

我在阅读数字分析时陷入了一个非常愚蠢的境地。

所以我在python中有以下程序。我无法理解为什么会得到这些结果。

我在哪里使用i中的heron(x,y)来获取这些结果?

因为只有第一个对我有意义。如果在函数中根本不使用i,为什么数字会减少?

def heron(x,y):
    x=(x+y/x)*0.5
    return x

x=1
y=2
for i in range(5):
   x=heron(x,y)
   print('Approximation of square root : %.16f'%x)

结果:

Approximation of square root :1.5000000000000000
Approximation of square root :1.4166666666666665
Approximation of square root :1.4142156862745097
Approximation of square root :1.4142135623746899
Approximation of square root :1.4142135623730949

编辑:代码是我的教授在课堂上给出的,我想它的唯一用途是解释Python的一些基本内容?

3 个答案:

答案 0 :(得分:3)

该行

for i in range(5):

仅表示:

  

做五次以上。

实际工作在

完成
x = heron(x,y)

使用x作为heron参数的一部分,并将更改后的值分配给它。因此,虽然y保持不变,但每次调用x时都会更改heron。然后将更改的x用作下一次调用的参数。

编辑:我无法确定这是否是正确的实现,因为我不知道您尝试实现的算法。但你只问:

  

如果在函数中根本没有使用i,为什么数字会减少?

答案 1 :(得分:0)

您正在尝试实施Heron's algorithm以查找数字的根平方。

这是一种迭代算法,您可以在每个步骤中提高结果的精度。

在您的实施中,x是初始解决方案,y是您要查找根方的数字。

您正在进行5次迭代,并且不需要变量i来进行迭代。您可以使用_声明一个不需要的变量。

您可以定义所需的精度并迭代多次以达到所需的精度。

def heron(x,y):
    x=(x+y/x)*0.5
    return x

x=1
y=2
numberOfIterations = 5
for _ in range(numberOfIterations):
    x=heron(x,y)
    print('Approximation of square root : %.16f'%x)

答案 2 :(得分:-1)

我认为,您必须修改您的代码,如下所示: -

def heron(x,y):
    x=(x+y/x)*0.5
    return x

x=1
y=2
for i in range(5):
   z=heron(x,y)
   print 'Approximation of square root :%.16f'%z