【问题标题】:Python - Differential equation, initial condition problemPython - 微分方程,初始条件问题
【发布时间】:2021-02-15 19:34:32
【问题描述】:

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

【问题讨论】:

  • 您能否详细说明确切您希望Qout 何时= 2?只有在yrez恰好达到5之后吗?或者只要 yrez >= 5?

标签: python differential-equations


【解决方案1】:

为此,您必须使用所谓的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

视觉表现:

【讨论】:

  • 这似乎奏效了,谢谢!如果应用高 Qout,它是否有可能突然跳跃导致 yrez 从 5 变为 0.5,比如说,即使边界线是 1?
【解决方案2】:

您的代码的问题是,一旦 yrez 低于 5,它就不会进入内部 while 循环。再次调用该函数不会在最后一次“返回”处继续,而是从函数的开头开始。

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

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

【讨论】:

  • 我得到这个错误:__call__(self, yrez): ^ SyntaxError: invalid syntax
  • 抱歉我的代码有错误(忘记了 call 方法中的 def 和 yrez),现在应该可以工作了
猜你喜欢
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 2018-06-26
相关资源
最近更新 更多