2015-10-14 133 views
0

我遇到了嵌套在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() 

所以我需要這個陣列上對日誌相應明尼蘇達州值的圖表繪製。有什麼想法嗎?

+1

簡短回答:因爲'math.fabs(fx_2)> minn [i]'在第一次迭代後不是真的。 – tenwest

+0

我認爲很多初始化(例如,'x_3 = 3'等)必須在for循環中發生,就在while循環之前,因此在for循環的每次迭代中,初始狀態都會重置。但也許我誤解了這個程序的概念。如果沒有詳細的解釋這將會完成什麼,這很難猜測。 – Alfe

+0

非常感謝,這是我錯過的。現在完美工作。 –

回答

0

我調試了你的程序。 在第一個for循環交互之後,while循環運行17次。 i從0遞增到1,並嘗試再次評估while循環。

在這個pointvalue的fx_2這裏是-8.63145396579057e-06minn[1]6.0000000000000002e-05

所以fx_2的絕對值大於少min[i]其中i==1,因此不允許再次進入內環路,吐出零代替nsteps

由於我不是一個數學知識,我建議你再看看你想要計算的東西。

+0

嗨,非常感謝你的回覆。我最終弄明白了自己,這是一個非常明顯的細節!我沒有重置我的x_1和x_3兩個值。在for循環中添加已修復了我的錯誤。感謝您花時間回覆 –