当我尝试在 if 语句体内分配变量 x 时,如果该变量也出现在 if 语句的条件中,我会得到意外的结果。
例如代码
model algorithmTest_25p05p2021
Real x(start=0);
Real y(start=0);
algorithm
y := sin(time);
x := sin(time);
if x < 0 then // replace with y < 0 --> x is correctly truncated
x := 0;
end if;
end algorithmTest_25p05p2021;
我在OpenModelica 1.17.0中使用OMEdit,仿真时间120s,最大步进时间1s。 我无法理解这里发生的事情。
根据我的理解,算法部分意味着x被初始化为其起始值0。初始化后,我认为算法部分中的语句是按顺序执行的。因此,在 if 语句之前,x 被设置为 x=sin(time) 的值。 之后,我预计 if 语句将在 sin(time) < 0 时设置 x=0,并在 sin(time)>=0 时将 x 保留为 x=sin(time)。
您会看到发生了什么:条件第一次触发后 x 保持为零。
更让我困惑的是,用“y<0”条件替换“x<0”条件可以解决问题。
我在这里错过了什么?有任何关于 Modelica 规范的指示吗?
编辑(2021 年 5 月 27 日): 由于此行为似乎是 OpenModelica 1.17.0 中的一个错误,我将其发布到他们的 Github 上,请参阅 https://github.com/OpenModelica/OpenModelica/issues/7484
最佳答案
这一定是一个错误。
显然应该有一个关于 x<0
的事件,但事件逻辑仅在 x
时才重要。接近于零,因此对图形的影响应该很小。
我能找到的规范的相关部分是:
- 仅在 true 时才评估 If 语句 https://specification.modelica.org/maint/3.5/statements-and-algorithm-sections.html#if-statement
- 如果条件和隐藏状态不一致,则会生成事件: https://specification.modelica.org/maint/3.5/equations.html#events-and-synchronization
- 概念上
x
使用其起始值进行初始化,但这并不重要,因为它是无条件分配的 https://specification.modelica.org/maint/3.5/statements-and-algorithm-sections.html#execution-of-an-algorithm-in-a-model
关于if-statement - if 语句中的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67692496/