2015-12-13 82 views
-1

我有以下腳本:如何執行,如果內的循環語句,只有當條件滿足

import numpy as np 
import matplotlib.pyplot as pl 

time=np.linspace(0.,1825,1826) 
#temp with peak at midpoint of year 
T=23*np.sin((2*np.pi*time)/365)+1 
#drainage basin area 
A=8.094e10 
#surface area of pond in mm 
SA= 2.023e9 
#hydraulic conductivity in mm/day/mm 
K=2e-3 
#GW level mm 
Hgw=-2000 

def precipPond(dayt): 
    ''' 
    Input day with time notation for 365 days... 
    eg time[0] is dayt 1, time[1] is dayt 2, etc. 
    ''' 
    #P varies from 0.2 mm/day to 1.8 mm/day with a peak at 120 
    P=np.sin(((2*np.pi*dayt)/365)+120)+0.8 
    #15 percent of all P flows into pond (mm) 
    infilP=(P*A*0.15) 
    return infilP 
def evapoTrans(dayT): 
    ''' 
    Input day with time notation for 365 days... 
    eg T[0] is temp at dayT 1, T[1] is temp at dayT 2, etc. 
    ''' 
    #saturated vapor pressure for ET equation 
    et=0.611*(np.exp((17.3*dayT)/(dayT+237.3))) 
    #evapotranspiration 
    ET2=29.8*12*(et)/(dayT+273.2) 
    #return factor*ET2 
    return ET2 

Hp=np.zeros(1826.) 
Hp2=[] 
precip=[] 
evapoT=[] 
def waterBudget(HpI,delt): 
    ''' 
    Put in initial water level and change in time. 
    ''' 
    #Save the initial water level in the first position 
    Hp[0]=HpI 
    steps=(len(time)-1) 
    factor=1 
    for i in range(steps): 
     #Get the mid point value, which will be used to estimate derivative 
     HpMid=Hp[i]+(delt/2)*(K*SA*((Hgw-Hp[i])/SA)+precipPond(time[i])+((SA*(precipPond(time[i])/A))*0.85)-(evapoTrans(T[i])*factor*SA)) 
     #Find the derivative for dh/dt 
     Hp[i+1]=Hp[i]+delt*(K*SA*((Hgw-HpMid)/SA)+precipPond(time[i])+((SA*(precipPond(time[i])/A))*0.85)-(evapoTrans(T[i])*factor*SA)) 
     if any(HpMid < 0): 
      factor=0 
     else: 
      factor=1 
    return Hp 
ET=evapoTrans(T) 
infilP=precipPond(time) 
Hp=waterBudget(0,1) 

我想在循環中的if語句(函數waterBudget內),使ET爲零時HpMid是零下。我運行這個腳本,即使當我改變腳本使HpMid低於零時(**我沒有在這裏包含這個腳本),它也使得整個時間都成爲因子1。

+1

你設置'因素',但它無處使用。這是我看到的第一個問題。它也看起來像你試圖調用浮動上的任何一個。其餘的太過複雜以至於無法理解。請爲你正在嘗試做的事情創建一個最低限度的例子。 – timgeb

回答

1

地說:

Hp[i+1]=Hp[i]+delt*(...) 

if語句:

HpMid=Hp[i]+(delt/2)*(K*SA*((Hgw-Hp[i])/SA)+precipPond(time[i])+((SA*(precipPond(time[i])/A))*0.85)-(evapoTrans(T[i])*SA)) 
if HpMid < 0: 
    Hp[i+1] = delt*(K*SA*((Hgw-HpMid)/SA)+precipPond(time[i])+((SA*(precipPond(time[i])/A))*0.85)-(evapoTrans(T[i])*SA)) 
else: 
    Hp[i+1]=Hp[i]+delt*(K*SA*((Hgw-HpMid)/SA)+precipPond(time[i])+((SA*(precipPond(time[i])/A))*0.85)-(evapoTrans(T[i])*SA)) 

,你可能也想看看PEP8進行格式化,它會讓你的代碼更易於閱讀,因此,更容易調試並重用。

0

這種情況看起來不對if any(HpMid < 0)。你可以找到any()函數做什麼here。在你的情況下,HpMid看起來像是一個保存雙重計算結果的簡單變量。所以只是做if HpMid < 0:

+0

如果我取出任何(HpMid <0),我會得到以下錯誤: ValueError:具有多個元素的數組的真值是不明確的。使用a.any()或a.all() – Strak

相關問題