user578943
user578943

Reputation: 103

Assignment of variable within if-statement

When I try to assign a variable x within the body of an if-statement I get unexpected results if the variable also occurs in the condition of the if-statement.

For example, the code

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;

results in enter image description here

I used OMEdit in OpenModelica 1.17.0, simulation time 120s, maximum step time of 1s. I can't wrap my head around what is going on here.

In my understanding, the algorithm section implies that x is initialized to its start value 0. After initialization, I thought the statements in the algorithm section are executed in order. So, before the if-statement, x is set to the value of x=sin(time). Afterwards, I expected that the if-statement would set x=0 if sin(time) < 0 and leave x to be x=sin(time) if sin(time)>=0.

You see what happens instead: x stays zero after the condition triggers for the first time.

What confuses me even more is that replacing the "x<0"-condition with a "y<0"-condition fixes the issue.

What have I missed here? Any pointers to the Modelica specification?

EDIT (27.05.2021): As this behaviour appears to be a bug in OpenModelica 1.17.0, I posted it on their Github, see https://github.com/OpenModelica/OpenModelica/issues/7484

Upvotes: 2

Views: 254

Answers (1)

Hans Olsson
Hans Olsson

Reputation: 12517

It must be a bug.

Clearly there should be an event for x<0, but the event-logic is only important when x is close to zero and thus should have a minimal impact on graph.

The relevant sections of the specification I can find are:

Upvotes: 2

Related Questions