[英]Python - Differential equation, initial condition problem
我正在嘗試實現一個控制微分方程的 function。
為此,您必須使用所謂的有限狀態機。 這基本上意味着您必須存儲一個 state,它可以根據輸入而改變,並影響 output。
在這種情況下:
#State variable
qout_state = 0
def Qout(yrez):
#Declare that we will be using the global variable
global qout_state
#If the input is >= 5, change the state to 1 and return 2.
if yrez >= 5:
qout_state = 1
return 2
#If the input is <= 1, change the state to 0 and return 0.
if yrez <= 1:
qout_state = 0
return 0
#If the input doesn't make any of the previous statements true, use the stored state:
#If the state is 1, it means that the previous input wasn't <= 1, so we are on "return 2" mode
if qout_state == 1:
return 2
#If the state is 0, it means that the previous input wasn't >= 5, so we are on "return 0" mode
if qout_state == 0:
return 0
視覺表現:
您的代碼的問題是,一旦 yrez 低於 5,它就不會是內部 while 循環。 再次調用 function 不會在最后一次“返回”處繼續,而是從 function 的開頭開始。
不確定它是否有效,但您可以嘗試使用可調用的 class object 而不是 function,它可以保存您的局部變量:
class Qout_class():
condition = False
def __call__(self, yrez):
if (yrez >= 5):
self.condition = True
elif (yrez < 1):
self.condition = False
if self.condition:
return 2.
else:
return 0.
Qout = Qout_class()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.