我遇到了嵌套在for循环中的while循环的问题。它在for循环的第一次迭代中完美执行,但for循环在所有其他迭代上跳过while循环。while循环嵌套在for循环中仅执行for循环的第一次迭代
我想用for循环的每个迭代的while循环执行次数nsteps填充列表nsteps_list。一个预期的答案将会像List = [17,16,16,14,15,13,12,15 ...]那样,但是发生的所有事情是List = [17,0,0,0,0,0 ...]
循环代码在这里:
# Bisection Method
minn = np.arange(.00001, .001, 0.00005)
nsteps_list = [0.0] * (len(minn)) # Rewrite each index with nsteps as iterating through
nsteps = 0
for i in range(0, len(minn) - 1):
while math.fabs(fx_2) > minn[i]:
if fx_2 > 0:
x_3 = x_2
print "UPDATE: x_3 = " + str(x_2)
elif fx_2 < 0:
x_1 = x_2
print "UPDATE: x_1 = " + str(x_2)
x_2 = 0.5 * (x_1 + x_3)
fx_2 = func(x_2)
nsteps += 1
print nsteps
nsteps_list[i] = nsteps
nsteps = 0
print "List: " + str(nsteps_list)
我从尝试,它通过对循环迭代精细知道,但它未能返回到while循环,所以n步来重置0从不改变,我的列表填充0。
以下是完整的代码,在上下文中:
#!/usr/bin/python
import matplotlib.pylab as plt
import numpy as np
import math
# Parabola = 3x^2-9x+2 ==> Has minimum and 2 real roots
def func(n): # Defining function to get f(x) for each x for parabola
a = 3
b = -9
c = 2
fx = a * n * n + b * n + c
return fx
# Calling parabola function on values in x
x = np.arange(-2.0, 4.0, 0.2)
y = func(x)
plt.figure(1)
plt.plot(x, y)
plt.plot(x, x * 0)
# Declare Variables for bisection method
x_1 = 2.0
x_3 = 3.0
x_2 = 0.5 * (x_1 + x_3)
fx_1 = func(x_1)
fx_2 = func(x_2)
fx_3 = func(x_3)
if fx_1 >= 0:
print "Warning: Variable x_1 not initialised correctly."
if fx_3 <= 0:
print "Warning: Variable x_3 not initialised correctly."
# Bisection Method
minn = np.arange(.00001, .001, 0.00005)
nsteps_list = [0.0] * (len(minn)) # Rewrite each index with nsteps as iterating through
nsteps = 0
for i in range(0, len(minn) - 1):
while math.fabs(fx_2) > minn[i]:
if fx_2 > 0:
x_3 = x_2
print "UPDATE: x_3 = " + str(x_2)
elif fx_2 < 0:
x_1 = x_2
print "UPDATE: x_1 = " + str(x_2)
x_2 = 0.5 * (x_1 + x_3)
fx_2 = func(x_2)
nsteps += 1
print nsteps
nsteps_list[i] = nsteps
nsteps = 0
print "List: " + str(nsteps_list)
print "x_2 = " + str(x_2) + " and f(x_2) = " + str(fx_2) + "."
plt.figure(2)
plt.plot(np.log10(minn), nsteps_list)
plt.figure(1)
plt.plot(x_2, fx_2, "mo")
plt.show()
所以我需要这个阵列上对日志相应明尼苏达州值的图表绘制。有什么想法吗?
简短回答:因为'math.fabs(fx_2)> minn [i]'在第一次迭代后不是真的。 – tenwest
我认为很多初始化(例如,'x_3 = 3'等)必须在for循环中发生,就在while循环之前,因此在for循环的每次迭代中,初始状态都会重置。但也许我误解了这个程序的概念。如果没有详细的解释这将会完成什么,这很难猜测。 – Alfe
非常感谢,这是我错过的。现在完美工作。 –