Search code examples
if-statementmodelica

Using an if-statement for div by 0 protection in Modelica


I made a simple model of a heat pump which uses sensor data to calculate its COP.

while COP = heat / power

sometimes there is no power so the system does a (cannot divide by zero). I would like these values to just be zero. So i tried an IF-statementif-statement. if power(u) = 0 then COP(y) = 0. somehow this does not work (see time 8)COP output + data. Anyone who seems to notice the problem?

edit(still problems at time 8.1 output2.o textview 2.0 edit(heat and power) heat/power/COP


Solution

  • To make the computation a bit more generally applicable (e.g. the sign of power can change), take a look at the code below. It could also be a good idea to build a function from it (for the function the noEvent()-statements can be left out)...

    model DivNoZeroExample
          parameter Real eps = 1e-6 "Smallest number to be used as divisor";
          Real power = 0.5-time "Some artificial value for power";
          Real heat = 1 "Some artificial value for heat";
          Real COP "To be computed";
    
    equation 
        if noEvent(abs(power) < abs(eps)) then
            COP =  if noEvent(power>= 0) then heat/eps else heat/(-eps);
        else
            COP =  heat/power;
        end if;
    end DivNoZeroExample;