Please note that ExpatTech is close for the Christmas and New Year holidays. We will re-open on 2nd January 2024.

ExpatTech Techblog

Peter Todd 2010.09.23. 15:49

Fun with Random - Part 1.

This section we will write a basic random generator. Of course this is a pseudo-random too, and we will build just the basics. Code written in Flash AS3.

First of all we will initiatize our random generator

var a:Number = (new Date()).getTime();
var count:Number = 0;

We have to get some kind of a random in the beginning, therefore we use Date. The function above gets the number of milliseconds since midnight January 1, 1970. We could use a built-in random function here, but now we want to avoid it.

 

Then look at the main function:

function getRandom():Number
{
    a += a * count++;
    var res:Number = a % 1009;
    if(a > Math.pow(10, 250)) a = 1, count = 0;
    res = res / 1009;
    return res;
}

This basically increases the value of "a" and then gets modulo 1009. Note that 1009 is a prime number (and modulo is the standard function for getting the remainder of a division).

After doing the modulo it checks whether "a" is bigger then a given value, if true it reduces its value (here the repetition starts, so the whole set won't be random).

After that, it devides this value with the given prime, resulting a number greater than zero, but smaller than 1 (never 1 actually).

Example results:

0.062438057482656094
0.12487611496531219
0.37462834489593655
0.4985133795837463
0.49256689791873143
0.9554013875123885
0.6878097125867195
0.5024777006937562
0.5222993062438057
0.4767096134786918

another set of results:

0.36174430128840435
0.7234886025768087
0.17046580773042616
0.6818632309217046
0.4093161546085233
0.45589692765113976
0.19127849355797819
0.5302279484638256
0.7720515361744301
0.22794846382556988

Special thanks to DarthJDG, who noted two things:

1.) the algorithm won't generate random series, if your current time is midnight January 1, 1970 (resulting zero for initializing a:Number), or a constant date (will always use the same initialization).

2.) also as was expected, after the overflow (the conditional in the algorithm), the numbers become periodic and the whole process won't be random anymore.