if 语句中的变量赋值
Assignment of variable within if-statement
当我尝试在 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
一定是bug。
显然 x<0
应该有一个事件,但事件逻辑仅在 x
接近于零时才重要,因此对图表的影响应该很小。
我能找到的规范的相关部分是:
- 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 语句的主体中分配变量 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
一定是bug。
显然 x<0
应该有一个事件,但事件逻辑仅在 x
接近于零时才重要,因此对图表的影响应该很小。
我能找到的规范的相关部分是:
- 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