Jack Hsueh
Jack Hsueh

Reputation: 125

less than or equal not equal less than or equal in modelica?

I tried a simple example with OpenModelica v1.20.0, but I find a confusing results.

The code is as follows:

model test
  Boolean state1;
  Boolean state2;
  Real f;
equation
  f = if time<1 then 0.5 else if time<3 then 0.4 else if time<5 then 0.3 else if time<7 then 0.4 else 0.5;
  state1 = f<=0.4;
  state2 = f<0.4 or f==0.4;
end test;

And the corresponding result is as follows: simulation result

Obviously, the result of state1(<=) is not equal state2(< or ==), and state1 is not a desired result.

Why?

Upvotes: 3

Views: 375

Answers (2)

Christoph
Christoph

Reputation: 5612

I suspect floating-point issues, although behaviour remains weird.

I fixed a translation warning about using == with Reals outside a function (you should see that too), but behaviour is the same as in your plot. I also tried to make sure all comparisons use the same parameter 0.4, to avoid floating-point inaccuracies between the different 0.4 literals, and scaled f with a nominal attribute.

Even using <= for both state1 (in the equation section) and state2 (set by a function) does not produce the same plot for both state1 and state2.

model test
Boolean state1;
Boolean state2;
parameter Real threshold = 0.4;
Real f(nominal=0.5);

  function compare
  input Real a;
  input Real b;
  output Boolean res;
  algorithm
  res := a < b or a == b;
  //res := a <= b; // Even this does not produce the same result as state1
  end compare;
equation
  f = if time<1 then 0.5 else if time<3 then threshold else if time<5 then 0.3 else if time<7 then threshold else 0.5;
  state1 = f<=threshold;
  state2 = compare(f, threshold);

annotation(
    experiment(StartTime = 0, StopTime = 10, Tolerance = 1e-06, Interval = 0.02));
end test;

Edit: this seems connected to event resolution, I opened a bug report about the behaviour of the <= operator at https://github.com/OpenModelica/OpenModelica/issues/9140

For now, you can work around it by using state1 = noEvent(f<=threshold);, instead. This seems to work correctly in OM, too.

Edit/Resolution: The issue has been clarified with a comment -- you should probably not write Modelica like that. A less synthetic example might help solve the underlying modelling issue you have.

Upvotes: 3

Hans Olsson
Hans Olsson

Reputation: 12507

There are some things to consider in Modelica:

The reason I write ideally is that it is not always possible to guarantee that relations are handled literally at events. That was specified in Modelica up to version 3.2; but did not work in all cases in practice and has thus later been removed.

Upvotes: 5

Related Questions