Assignment problems with simple random number generation in Modelica

守給你的承諾、 提交于 2019-12-11 12:41:26

问题


I am relatively new to Modelica (Dymola-environment) and I am getting very desperate/upset that I cannot solve such a simple problem as a random number generation in Modelica and I hope that you can help me out.

The simple function random produces a random number between 0 and 1 with an input seed seedIn[3] and produces the output seed seedOut[3] for the next time step or event. The call (z,seedOut) = random(seedIn); works perfectly fine.

The problem is that I cannot find a way in Modelica to compute this assignment over time by using the seedOut[3] as the next seedIn[3], which is very frustrating.

My simple program looks like this:

*model Randomgenerator
Real z;
Integer seedIn[3]( start={1,23,131},fixed=true), seedOut[3];
equation
  (z,seedOut) = random(seedIn);
algorithm
  seedIn := seedOut;

end Randomgenerator;*

I have tried nearly all possibilities with algorithm assignments, initial conditions and equations but none of them works. I just simply want to use seedOut in the next time step. One problem seems to be that when entering into the algorithm section, neither the initial conditions nor the values from the equation section are used.


回答1:


Using the 'sample' and 'reinit' functions the code below will calculate a new random number at the frequency specified in 'sample'. Note the way of defining the "start value" of seedIn.

model Randomgenerator

  Real seedIn[3] = {1,23,131};

  Real z;
  Real[3] seedOut;

equation 
  (z,seedOut) = random(seedIn);
  when sample(1,1) then
   reinit(seedIn,pre(seedOut));
  end when;

end Randomgenerator;

The 'pre' function allows the use of the previous value of the variable. If this was not used, the output 'z' would have returned a constant value. Two things regarding the 'reinint' function, it requires use of 'when' and requires 'Real' variables/expressions hence seedIn and seedOut are now defined as 'Real'.

The simple "random" generator I used was:

function random

  input Real[3] seedIn;

  output Real z;
  output Real[3] seedOut;

algorithm 
  seedOut[1] :=seedIn[1] + 1;
  seedOut[2] :=seedIn[2] + 5;
  seedOut[3] :=seedIn[3] + 10;

  z :=(0.1*seedIn[1] + 0.2*seedIn[2] + 0.3*seedIn[3])/(0.5*sum(seedIn));

end random;

Surely there are other ways depending on the application to perform this operation. At least this will give you something to start with. Hope it helps.



来源:https://stackoverflow.com/questions/36265293/assignment-problems-with-simple-random-number-generation-in-modelica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!