Wei
Wei

Reputation: 87

When and If in Modelica

Hi I have some puzzles about event and when in Modelica. Below is my code:

model test
  Integer bar(start=5, fixed=true);
equation 
  when (time < 2) then
    bar = 1;
  end when;
  annotation(experiment(StopTime=3));
end test;

My question is why I got 5 instead of 1 when time is less than 2? How can I understand the event(time < 2) in this case? What is the difference of when clause in Modelica and other programming language, like c.

Upvotes: 1

Views: 1740

Answers (2)

Tobias
Tobias

Reputation: 5198

The when equation is only active when the condition becomes true. In your case the condition time < 2 is true from the beginning and only becomes false.

The when-block can be intentionally translated to

b = time < 2;

if not(pre(b)) and b then
  bar = 1;
else
  bar = pre(bar);
end 

For further information you can consult the specification https://modelica.org/documents/ModelicaSpec33Revision1.pdf.

Upvotes: 2

Michael Tiller
Michael Tiller

Reputation: 9421

Tobias' answer is correct. But I think for beginners it might be a little daunting to invoke the pre construct or send them to the specification. So in addition to Tobias' answer, I would point the interested reader to this question as well as this chapter in my book. Of specific interest (I suspect) would be this subsection on when and how it is different from if.

Upvotes: 1

Related Questions