简体   繁体   English

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

[英]Python - Differential equation, initial condition problem

I am trying to implement a function that controls the differential equation.我正在尝试实现一个控制微分方程的 function。

To do this, you have to use a so called finite-state machine .为此,您必须使用所谓的有限状态机 This basically means you have to store a state which can change depending on the input, and affects the output.这基本上意味着您必须存储一个 state,它可以根据输入而改变,并影响 output。

In this case:在这种情况下:

#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

Visual representation:视觉表现:

在此处输入图像描述

The problem with your code is that once yrez falls below 5, it will not the inner while loop.您的代码的问题是,一旦 yrez 低于 5,它就不会是内部 while 循环。 Calling the function another time does not continue at the last "return" but starts at the beginning of the function.再次调用 function 不会在最后一次“返回”处继续,而是从 function 的开头开始。

Not sure if it works, but you can try a callable class object instead of a function, which saves your local variable:不确定它是否有效,但您可以尝试使用可调用的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM