Python - 微分方程,初始条件问题

Python - Differential equation, initial condition problem

我正在尝试实现一个控制微分方程的函数。

为此,您必须使用所谓的 finite-state machine。这基本上意味着你必须存储一个状态,它可以根据输入而改变,并影响输出。

在这种情况下:

#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 循环。下次调用该函数不会从最后一个“return”继续,而是从函数的开头开始。

不确定它是否有效,但您可以尝试使用可调用的 class 对象而不是函数,这样可以保存您的局部变量:

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()