CancelImage Upload

So you want real random numbers in PHP? rand & srand vs. mt_rand & mt_srand

If you are like me you probably once upon a time spotted that PHP had a random number generating function called rand(), decided to save it to your memory, and left it at that. After all, a random number is a random number. Why would a programming language need more than one random number generating function?

Well, apparently the creators of PHP did once upon a time decide one random number generating function is not enough.

Instead they decided to leave rand() for the simpleton peasants like myself:

echo rand(0, 99999);

Then for the more curious programmer they invented a fun function called srand(), which as far as I can tell acts like the lottery ball machine, shooting numbers all over the place before rand() lets them out of their cage:

srand((double)microtime()*1000000);

echo rand(0, 99999);

Now most developers would leave it at that and celebrate a job well done. But I guess a true PHP expert needs more.

Like a good wine this is one for your connoisseur: mt_rand()!

This function is stronger, faster and apparently has the looks of a Greek god. And while rand() can only deliver random numbers between 0 and 32767, mt_rand() can do some true heavy lifting in the number generating world: 0 - 2147483647. Wow, anyone who has been using simple little rand() all these years will feel like crying right about now.

echo mt_rand(0, 99999);

It gets worse though. For some apparently mt_rand() alone was not enough. For the super geek out there something special and out of the ordinary was needed: mt_srand()!

Some say numbers simply fall out of existence itself when this baby is put into motion.

Others believe it could actually tear a black hole into existence!

mt_srand((double)microtime()*1000000);

echo mt_rand(0, 100);

Well, I tried it, and no black hole was produced. In fact, using the following code I let these functions go at each other, and I can't say there was that much of a difference.

I am sure that if a comparison was done on a larger scale a significant difference would become apparent thanks to mt_rand() and mt_srands()'s far more complex algorithms.

But on the other hand, think of how much quicker it is to simply type rand()! You can save yourself a full split second there!

Now that is fast!

<?php

echo "<b>rand() without srand()</b><br><br>";

for($i = 0; $i != 5; $i++)
{

echo rand(0, 100)."<br><br>";

}

srand((double)microtime()*1000000);

echo "<b>rand() with srand()</b><br><br>";


for($i = 0; $i != 5; $i++)
{

echo rand(0, 100)."<br><br>";

}

echo "<b>mt_rand() without mt_srand()</b><br><br>";

for($i = 0; $i != 5; $i++)
{

echo mt_rand(0, 100)."<br><br>";

}

mt_srand((double)microtime()*1000000);

echo "<b>mt_rand() with mt_srand()</b><br><br>";


for($i = 0; $i != 5; $i++)
{

echo mt_rand(0, 100)."<br><br>";

}

?>

The results:
rand() without srand()

51

31

69

21

72

rand() with srand()

6

62

45

28

61

mt_rand() without mt_srand()

11

81

23

8

40

mt_rand() with mt_srand()

95

80

23

38

14


Need help with some code? Post a help thread as guest:
Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder
Posted by Garren Harland on September 7, 2009, 11:41 am.
If you are writing a PHP application that is dealing with data related to weather conditions you will no doubt at some point have to convert between Celsius and Fahrenheit. To perform these conversions two simple formulas are required.
Click here to read on.
Posted by Garren Harland on September 7, 2009, 10:52 am.
England has never been a country willing to fit in. Never has there been any interest in driving on the right hand side of the road, and when asked how many kilograms are found within a Stone, the reply will often be along the lines of.
Click here to read on.
Posted by Garren Harland on August 31, 2009, 11:36 am.
The following tutorial discusses how the metric unit meters can be converted into yards and feet with the help of PHP. Naturally enough these same conversion numbers can be used to perform the conversion in other programming languages.
Click here to read on.
Posted by Garren Harland on August 31, 2009, 10:37 am.
This tutorial will discuss how Kilograms (KG) can be converted into stones or Pounds with PHP. Especially the stones are easy to calculate from KG, once the number of pounds has been established. For the sake of accuracy this in-between step can be seen as a necessary one.
Click here to read on.
Posted by Garren Harland on August 5, 2009, 2:54 pm.
If you are looking for the value of a specific percentage of a number in PHP all you need is some basic maths. For instance, if you want to find out 5% of 100, simply multiply 100 times .05. Here are a few examples to try out.
Click here to read on.
Posted by Garren Harland on August 5, 2009, 2:33 pm.
Here is a useful bit of code for testing whether or not a number is dividable by a specified value. In our example below we will go through a "for" loop, checking every number to see if it can be divided by 5. If yes we will print it, if not we shall skip it and go on to the next.
Click here to read on.
Posted by Garren Harland on August 3, 2009, 3:13 pm.
Sometimes all you need from a string are certain elements. Such an element can be a hidden number which has significance to you. Maybe a timestamp for instance.
Click here to read on.
Posted by Garren Harland on August 3, 2009, 11:17 am.
When working with divisions the remainder is often required. This is often important for subsequent calculations, such as the conversion from seconds into days, minutes and hours.
Click here to read on.
Posted by Garren Harland on July 21, 2009, 5:17 pm.
Previously I have discussed how additions, subtractions, multiplications and divisions can be performed using bc functions with the results being produced to a specified decimal point.
Click here to read on.
Posted by Garren Harland on July 21, 2009, 4:57 pm.
Here are four PHP maths functions that might come in handy. If for instance you have to perform a simple addition, subtraction, division or multiplication, and want the result to be rounded to a specific decimal point, here is how you can do it.
Click here to read on.
Posted by Garren Harland on July 13, 2009, 11:17 pm.
In order to convert negative numbers into positives in PHP one simple function is required: abs(). The abbreviation abs stands for absolute values, and works like this.
Click here to read on.
Posted by Garren Harland on July 13, 2009, 11:00 pm.
Here is a function that could come in handy with numbers games. More specifically: numbers games where the winner is the person who has guessed the closest number to an end result.
Click here to read on.
Posted by Garren Harland on July 13, 2009, 1:00 pm.
This tutorial will teach you on the one hand how to convert decimal numbers into hexadecimals codes and vise versa, while at the same time having a closer look at the format of HTML Color codes.
Click here to read on.
Posted by Garren Harland on July 13, 2009, 10:42 am.
Here is the predefined PHP function that can calculate your square routs.
Click here to read on.
Posted by Garren Harland on July 11, 2009, 8:50 pm.
The function asin() can be used to calculate the Sinus Arch in PHP. Simply insert the value in between the brackets and let PHP take care of the rest for you.
Click here to read on.
Posted by Garren Harland on July 11, 2009, 6:58 pm.
As with most mathematical requirements PHP already has a function in place to help deliver your results. And even for Cosine Arch calculations PHP is not a let down.
Click here to read on.
Posted by Garren Harland on July 11, 2009, 6:15 pm.
PHP has the constants mentioned in the title and others already predefined. All you need is the right code to access them by!
Click here to read on.
Posted by Garren Harland on July 4, 2009, 8:57 pm.
Producing pi in PHP is even simpler than printing Hello World.
Click here to read on.
Posted by Garren Harland on July 4, 2009, 8:42 pm.
Previously I have written about the PHP function bindec(), and how it can convert a binary code into a decimal number. By reversing the function the opposite can be done, so changing bindec() into decbin() allows us to convert decimal numbers into binary code.
Click here to read on.
Posted by Garren Harland on July 4, 2009, 8:16 pm.
With the function bindec() you can translate a binary number into a decimal. Not that the largest convertible number (saved as a string) consists of 31 ones. This number equals the decimal value of 2147483647.
Click here to read on.
Posted by Garren Harland on July 4, 2009, 5:10 pm.
Looking for a PHP function to give you the greatest Common Divisor of two numbers? Then look no further. Although PHP does not as of yet provide such a function itself in its array of maths functions you can write a Greatest Common Divisor function yourself.
Click here to read on.
Posted by Garren Harland on July 4, 2009, 1:13 pm.
Are you in need of a PHP function that rounds numbers up to the closest integer? Then the function ceil() is your solution! Just insert the number that you need rounding up in between the brackets.
Click here to read on.
Posted by Garren Harland on July 3, 2009, 8:50 pm.
Do you need a PHP function to round down numbers down to the closest integer? Then floor() is the function you are looking for! To utilise the function insert the number that you need rounding down in between the brackets.
Click here to read on.
Everyday English GmbH • 8105 Regensdorf, Switzerland • Tel: +41 (0)44 840 03 68 • www.mydesigntool.cominfo@mydesigntool.com