April 23, 2013

Random Numbers Generation

02:33 Posted by Veera Bhadra , No comments
Random Number generation is very important aspect of many games, Cryptographic key generation and for other programs with a lot of outcomes. Let us take a look at how we generate those in C language and PHP. 
Before you proceed to the explanation, you need to know that a computer can never generate a Random number. It has to use some parameters to generate that number and so such numbers can never truly be Random. So, they are called Pseudo-Random Numbers and this tutorial deals with these. 

We have a built-in library function namely 'int rand(void )' in C. It gives the random number between 0 and RANDMAX. 
The value of RANDMAX is entirely library dependent, but it is guaranteed to be at least 32767 on any standard library implementation.

Then how to get numbers in the range we want ?
Let's say we want numbers only in between 100 and 1000. It is not directly possible with rand().
We have to use some of our math skills here with the use of  the operator , modulo (%).
I am very sure that you have used this operator before. It gives the remainder when one number is divided by another. (Check this tutorial if you are unsure)

The classy part of using this operator is that the remainder is always less than divider. So, the expression "X % 101" (X is some number) gives always a number less than 101 and greater than or equal to zero.

Let's come to our question , to generate numbers in between 100(101=min) and 1000(999=max) ,we need the expression
                                      result = rand( ) % 899 +101
where 899 is max-min+1 (999-101+1).


Post a Comment

Please Enter your comment here......