Search code examples
modelica

Questions about if, when, while statements


I would like to write a loop whose function is that when the value of c is less than 0.1, the loop terminates and outputs the value at the moment. Here's the code I wrote, I don't know when or while to use, thanks in advance for your reply

model Unnamed
 Real a;
 Real b;
 Real c(start=2);

algorithm 


 while abs(c)>0.1 loop
  a:=2*time-0.5;
  b:=time+0.1;
  c:=a-b;
 //  break;
 end while;

end Unnamed;


Solution

  • As far as I understand the algorithm and while-loop isn't important.

    What you want is to simulate as long as abs(c)>0.1 and then stop!

    That can be done as follows:

    model Unnamed
     Real a;
     Real b;
     Real c(start=2);
    algorithm 
     a:=2*time-0.5;
     b:=time+0.1;
     c:=a-b;
     when not abs(c)>0.1 then
       terminate("Reached end");
     end when;
    end Unnamed;
    

    This will stop after 0.5s. And as @marco noted it is generally preferable to use an equation instead of an algorithm - so just write:

    model Unnamed
     Real a;
     Real b;
     Real c(start=2);
    equation 
     a=2*time-0.5;
     b=time+0.1;
     c=a-b;
     when not abs(c)>0.1 then
       terminate("Reached end");
     end when;
    end Unnamed;