Home >Backend Development >PHP Problem >What is the difference between php mt_rand() and rand()

What is the difference between php mt_rand() and rand()

青灯夜游
青灯夜游Original
2021-10-19 18:40:252860browse

Difference: 1. If the parameter is omitted, the random number generated by rand() is between 0 and getrandmax(), while the random number generated by mt_rand() is between 0 and mt_getrandmax(); 2. The performance of mt_rand() is better than rand().

What is the difference between php mt_rand() and rand()

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

rand() and mt_rand() have both functions There are two forms of use to generate a random integer:

int rand() 
int mt_rand()
int rand(int $min, int $max)
int mt_rand($min, $max)

For the first form:

The random number generated by rand() is from 0 to Between getrandmax()

The random number generated by mt_rand() is between 0 and mt_getrandmax()

For the second form:

rand() generates a random number from $min to $max

mt_rand() generates a random number from $min to $max

Comparison:

mt_rand() is a better random number generator because it sows a better random number seed than rand(); and its performance is 4 times faster than rand(), mt_getrandmax( ) represents a larger numerical range

PS: Generation of random floating point numbers

There is a demo in the PHP manual

function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

var_dump(randomFloat());
var_dump(randomFloat(2, 20));

Recommended learning : "PHP Video Tutorial"

The above is the detailed content of What is the difference between php mt_rand() and rand(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn