Python:while循环中的for循环只运行变量

时间:2017-11-13 12:22:01

标签: python loops for-loop while-loop

所以这是我的问题:我有一个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

1 个答案:

答案 0 :(得分:3)

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)