Python:While循环在for循环中只运行for variab的第一个实例

2024-04-25 17:19:33 发布

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

所以我的问题是:我有一个for循环,变量k从1到31运行。在for循环中有一个while循环,它似乎只在第一个k中运行,没有其他循环。你知道吗

from numpy import exp

a = 0.0
N = 1
x = 0.1

def f(t):
    return exp(-t**2)

def int_trap(x,N):
    h = (x-a)/N
    s = 0.5*f(a) + 0.5*f(x)
    for i in range(1,N):
        s += f(a + i*h)
    return h*s

new_value = 1.0
old_value = 0.0

for k in range(1,11):
    x = k/10
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value))
    print(x)

最后的print(x)用于确认代码正在k中运行

输出结果如下:

2        0.1     0.900373598036
4        0.1     3.09486672713e-05
8        0.1     7.73536466929e-06
16       0.1     1.93372859864e-06
32       0.1     4.83425115119e-07
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

Tags: infromnumpynewforreturnvaluedef
1条回答
网友
1楼 · 发布于 2024-04-25 17:19:33

for循环在所有k值中运行良好。它不会通过while循环运行,可能是因为您没有重置new_value循环中的old_valuefor变量。如果我们在原始循环中添加一些要打印的内容:

for k in range(1,11):
    x = k/10
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value), 'In while for x={} and k={}'.format(x, k))
    print(x, '\tThis is me completing the loop for k=', k)

我们看到它正确地运行于所有k值:

2    0.1     0.900373598036 In while for x=0.1 and k=1
4    0.1     3.09486672713e-05 In while for x=0.1 and k=1
8    0.1     7.73536466929e-06 In while for x=0.1 and k=1
16   0.1     1.93372859864e-06 In while for x=0.1 and k=1
32   0.1     4.83425115119e-07 In while for x=0.1 and k=1
0.1     This is me completing the loop for k= 1
0.2     This is me completing the loop for k= 2
0.3     This is me completing the loop for k= 3
0.4     This is me completing the loop for k= 4
0.5     This is me completing the loop for k= 5
0.6     This is me completing the loop for k= 6
0.7     This is me completing the loop for k= 7
0.8     This is me completing the loop for k= 8
0.9     This is me completing the loop for k= 9
1.0     This is me completing the loop for k= 10

因此,请尝试以下方法:

for k in range(1,11):
    x = k/10
    new_value = 1.0
    old_value = 0.0
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value), 'In while for x={} and k={}'.format(x, k))
    print(x, '\tThis is me completing the loop for k=', k)

相关问题 更多 >