Reputation: 398
I wonder how PHP Rand() function works? I mean; How is this function randomising numbers without any rule or any other randomization function?
For example i have an array like this:
$numbers = array(0,1,2,3,4,5,6,7,8,9);
So how can i randomise this numbers without rand(), array_rand() etc..
Basic question is:
How randomization functions works?
Upvotes: 0
Views: 2193
Reputation: 1182
PHP rand()
, like all psuedo-random number generators, does not generate truly random data, but instead uses some mathematical function to create seemingly random data.
The methods may vary but the basic principle is this:
We take an initial value as a 'seed', s
. (This may be the current time, a user inputted "random" value, or even true random entropy harvested from some entropy source)
We then take s
and apply a function, f
, to it producing a new value s'
(s-prime) (this function is often a modulo function or hashing function)
We can then repeat this process ad infinitum, putting s'
into f
producing s''
, etc.
This sequence of results from f
are our "random" numbers.
But, hopefully you realized, f
remained the same and will always produce the same output given the same input.
So if we give it the same starting seed s
, we will always get the same sequence of s'
,s''
,s'''
...
This is why we call them "Psuedo" random. If you don't know the starting seed and don't observe the sequence for too long, it seems random. But if we know the function f
used and the starting seed s
we can predict every value rand()
would produce.
Upvotes: 5
Reputation: 179
Generally, It depends to the time based on the number of milliseconds or even nanoseconds. and we can multiplay the seed number with some fixed value to get a specific return, in most cases between 0 and 1 For exemple : Considering that numberis is a seed of seconds.
numberi+1 = (a * numberi + c) mod m
Upvotes: 0