简体   繁体   中英

Python - Differential equation, initial condition problem

I am trying to implement a function that controls the differential equation.

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.

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. Calling the function another time does not continue at the last "return" but starts at the beginning of the function.

Not sure if it works, but you can try a callable class object instead of a function, which saves your local variable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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