How does one generate a random float between 0 and 1 in PHP?
I'm looking for the PHP's equivalent to Java's Math.random()
.
How does one generate a random float between 0 and 1 in PHP?
I'm looking for the PHP's equivalent to Java's Math.random()
.
example:
result: 0.2
result: 3.219
result: 4.52
result: 0.69
You may use the standard function: lcg_value().
Here's another function given on the rand() docs:
Example from documentation :
Most answers are using
mt_rand
. However,mt_getrandmax()
usually returns only2147483647
. That means you only have 31 bits of information, while a double has a mantissa with 52 bits, which means there is a density of at least2^53
for the numbers between 0 and 1.This more complicated approach will get you a finer distribution:
Please note that the above code only works on 64-bit machines with a Litte-Endian byte order and Intel-style IEEE754 representation. (
x64
-compatible computers will have this). Unfortunately PHP does not allow bit-shifting pastint32
-sized boundaries, so you have to write a separate function for Big-Endian.You should replace this line:
with its big-endian counterpart:
The difference is only notable when the function is called a large amount of times:
10^9
or more.Testing if this works
It should be obvious that the mantissa follows a nice uniform distribution approximation, but it's less obvious that a sum of a large amount of such distributions (each with cumulatively halved chance and amplitude) is uniform.
Running:
Produces an output of
0.49999928273099
(or a similar number close to 0.5).