Archived OpenModelica forums. Posting is disabled.

Alternative forums include GitHub discussions or StackOverflow (make sure to read the Stack Overflow rules; you need to have well-formed questions)


Forgot password? | Forgot username? | Register

Problem with the If statement

Problem with the If statement

Hello

I am noticing a problem with the If-statement while writing my program. I eventually managed to correct it by using the sign function.

The problem observed is the value of variable 'a' when the variable 'fraction' becomes 1.

Please find attached both the codes below. Do notice the abrupt change in the value of 'a' when plotted against time.

Code:


model Test
  Real a;
  Real b;
  Real c(start = 90000);
  Real fraction;
  parameter Real d(start = 100000);
  annotation(experiment(StartTime = 0.0, StopTime = 3, Tolerance = 0.000001));
equation
  der(c) = 7500;
  fraction = c / d;
  if fraction <= 1 then
    b = 1;
  else
    b = -1;
  end if;
  a = fraction ^ (b / 2) * (4 * (1 - fraction ^ (b * 0.5))) ^ 0.5;
end Test;

The above code is the one containing the If-statement and the result is a sudden jump in the observed value of 'a'
Below is the code with the sign() function

Code:


model Test
  Real a;
  Real b;
  Real c(start = 90000);
  Real fraction;
  parameter Real d(start = 100000);
  annotation(experiment(StartTime = 0.0, StopTime = 3.0, Tolerance = 0.000001));
equation
  der(c) = 7500;
  fraction = c / d;
  b = sign(d - c);
  a = fraction ^ (b / 2) * (4 * (1 - fraction ^ (b * 0.5))) ^ 0.5;
end Test;

Thank you for going through the codes. The only difference is in the way the variable 'b' is assigned.

If anyone can help me and explain as to why this is happening I would be very grateful.

Also I wanted to know if this is a problem with the usage of equations and not algorithms whilst using the If-statement.

Thank You
Pratyush

Re: Problem with the If statement

Ok, I tried it in Wolfram System Modeler and get strange results, too. I don't really get it but there is an error message:

[error]: Invalid domain. pow(4.0 * (1.0 - fraction ^ (0.5 * b)), 0.5) evaluates to pow(-2e-10,0.5) "

ModelicaSpec3.3 says (p. 122):

Exponentiation "a^b" is defined as pow(double a,double b) in the ANSI C library if both "a" and "b" are Real
scalars. A Real scalar value is returned. If "a" or "b" are Integer scalars, they are automatically promoted to
122 Modelica Language Specification 3.3
"Real". Consequences of exceptional situations, such as (a==0.0 and b<=0.0, a<0 and b is not an integer) or
overflow are undefined

Re: Problem with the If statement

You want "if noEvent(fraction <= 1) then" since otherwise the if-equation will switch equation at a time that slightly differs from the exact zero-crossing.
I would probably have written it as "b = if noEvent(fraction <= 1) then 1 else -1;". Sign is defined as “noEvent(if v>0 then 1 else if v<0
then –1 else 0)”.

There are 0 guests and 0 other users also viewing this topic
You are here: