带for循环的简单函数

2024-05-20 17:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读数值分析时陷入了一个非常愚蠢的问题。你知道吗

所以我有下面的python程序。我不明白为什么我会得到这些结果。你知道吗

在哪里使用heron(x,y)中的i来获得这些结果?你知道吗

因为只有第一个对我有意义。如果函数中根本不使用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的一些基本东西?你知道吗


Tags: of函数in程序forreturndef数字
3条回答

我想,你必须修改你的代码如下:

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

您正在尝试实现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)

线路

for i in range(5):

仅表示:

Do the following five times.

实际工作是在

x = heron(x,y)

它使用x作为heron参数的一部分,并将更改后的值赋给它。因此,尽管y保持不变,但每次调用heronx都会发生变化。然后将更改后的x用作下一个调用的参数。你知道吗

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

Why are the numbers decreasing if the i isn't used at all at the function?

相关问题 更多 >