在阅读数字分析的时候,我陷入了一个非常愚蠢的观点。
所以我有下面的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的一些基本内容?
发布于 2016-11-01 09:46:11
线
for i in range(5):
仅指:
做以下五次。
实际工作是在
x = heron(x,y)
它使用x
作为heron
参数的一部分,并将更改后的值分配给它。因此,在y
保持不变的情况下,每次调用heron
都会更改x
。然后将更改后的x
用作下一次调用的参数。
编辑:,我无法确定这是否是一个正确的实现,因为我不知道您要实现什么算法。但你只问:
如果函数中根本没有使用i,为什么数字会减少呢?
发布于 2016-11-01 09:56:50
您正在尝试实现Heron算法以找到数字的平方根。
这是一种迭代算法,在每一步都会提高结果的精度。
在您的实现中,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)
发布于 2016-11-01 09:47:53
我认为,您必须修改您的代码如下:
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
https://stackoverflow.com/questions/40365587
复制