Reputation: 21
So here's my problem: I have a for
loop with a variable k
running from 1 to 31. Inside the for
loop there is a while
loop that seemingly only runs for the very first k
and no others.
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)
The print(x)
at the end is there to confirm that that the code is running through the k
's.
And here's the output:
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
Upvotes: 0
Views: 464
Reputation: 3012
The for
loop runs fine through all k
values. It doesn't run through the while
loop, perhaps because you don't reset the new_value
and old_value
variables inside the for
loop. If we add some things to print to the original loop:
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)
We see that it is correctly running for all k
values:
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
So try the following:
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)
Upvotes: 3