Monday, December 14, 2009

How to generate random numbers in Ax

Ax has functionality built-in to generate random numbers. You can use the Random class for this purpose. Like this:

static void RandomGenerator(Args _args)
{ Random Random = new Random();
int myrandomnumber;
;
myrandomnumber=1 + Random.nextInt() MOD 100;
info('Number '+int2str(myrandomnumber));
}

In the above example, Ax will generate a random number in the range from 1 to 100.
Though the random class gives you integer values, you can use it to generate random real values as well.

static void RandomGenerator(Args _args)
{ Random Random = new Random();
real myrandomnumber;
;
myrandomnumber=(1 + Random.nextInt() MOD 1000)/1000;
info('Number '+num2str(myrandomnumber,0,3,1,0));
}

This example generates random numbers in the range 0.001 to 1.000.

The use of this function comes with a warning:
The chosen numbers are not completely random because a definite mathematical algorithm is used to select them but they are sufficiently random for practical purposes.

So, good enough to use in an ERP system.

2 comments:

  1. You'd better use System.Random. The Random in AX does not use a seed and always returns the same random numbers

    ReplyDelete
    Replies
    1. To use a seed you can use the RandomGenerate class.
      For example:

      int i;
      int randomNumber;
      RandomGenerate randomGenerate;

      randomGenerate = RandomGenerate::construct();
      randomGenerate.parmSeed(new Random().nextInt());
      for (i = 1; i <= 10; i++)
      {
      randomNumber = RandomGenerate.randomInt(1, 6); // get a random integer between 1 and 6 inclusive
      }

      Delete