Sunday, December 9, 2007

Random numbers

Random numbers

A common problem is how you can use random numbers in programming and scripting languages. At the moment the random- function in JavaScript does not work but it soon going to be implemented, I believe. But at the moment you have to work with some tricks. Well, it is not really a trick. This is a really common way almost any compiler I can think of uses to calculate random numbers. Yes, it calculates it.

You take the time and date of your machine and manipulate it somehow. I believe the final JavaScript language will use this method (or a kind of it) as well. As I told you above the time is just a large number. You can use this number and make some calculations with it. For example you could calculate the sine from it and take the absolute value. This will get a number between 0 and 1. As the time changes every millisecond you won't risk to get the same number twice (when calculating them fast behind each other). If you want to calculate many random numbers in a short time you should not use sin() alone. Then you would get numbers following a sine- curve! This is not really random. But if you want to calculate a random number and let's say in 20 seconds again- this is a great function to do this.

Here is an sample output of this function. The number changes with every reload of the WWW-page:

This is a random number: 0.91936074496779396

Here is the code for this example:

Of course the random- function shown here isn't great for all puposes. It is just that you get a basic idea about how they work. Here I will present a function which I got from Maynard Demmon. You just have to set the limits variable to the value you need - 100 for example. And you will get a 'good' random value between 0 and 99. Here is the code:

function random() {

today = new Date();

num = today.getTime();

num = Math.round(Math.abs(Math.sin (num)*1000000)) % limits;

return num;

}

No comments: