Pages

Tuesday, April 26, 2011

Generating better random numbers with dynamics ax 2009

Inspired by this post, I created a neat little way to generate good random numbers between a range.

If you use AX Random class or RandomGenerate class to generate random numbers, you will find that if you do several in a row, they turn out fairly sequential.

The xGlobal::randomPositiveInt32() does a slightly better job of producing a random integer.

I would sometimes see patterns using this when the output is sorted:



static void Job6(Args _args)
{
    int total = 20;
    int i;
    ;
    
    while (total)
    {
        i = xGlobal::randomPositiveInt32();

        /*
        // This is better
        while (i > 9999999)
            i = i div 10;

        while (i < 1000000)
            i = i * 10;
        */
        
        while (i > 9999999)
            i = i >> 1;

        while (i < 1000000)
            i = i << 1;

        info(int2str(i));
        
        total--;

    }
}