4
votes

I was thinking, in PHP, you would use something like this:

rand(1, 100);

to generate a number between 1 and 100. If I was to use this code to get a random number with 4 decimal digits:

rand(1 * 10000, 100 * 10000) / 10000;

Would that make a difference in the probability and equality of getting a higher/lower number?

2
rand is one of the worst ways of getting a random number anyway, so... - Tim Seguine
No. rand() simply gives a pseudo-random number between the two ranges. Multiplying it first by a variable, then dividing by the same variable will make no difference to the outcome being higher or lower. - Fluffeh
You want 4 digit random number that is uniformly distributed? rand(1000,9999) will do that, although I would suggest using mt_rand(1000,9999) instead - Tim Seguine
the mt_rand function :) - DarkBee

2 Answers

2
votes

That will work (with one caveat), although I would still recommend using mt_rand instead of rand. The main difference is that mt_rand uses a different PRNG (pseudorandom number generator) engine that generally provides results that have better randomness than rand. Even so, this method has an issue, which you may or may not consider severe.

The potential issue comes from the floating point representation. Certain values are not representable in binary floating point, so they won't show up exactly in the output. Given the range of values you are generating though, the loss of precision shouldn't be significant. The only ways I see around this if it turns out to be a practical problem for you is fixed point arithmetic or binary coded decimals. I can explain their use if necessary.

In terms of the probability though (which is what you really asked), with this method each number from the interval [1,100] with at most 4 digits after the decimal point in its base 10 representation will be generated with equal probability if we neglect the approximation error. Of course, this is assuming the random number generator actually generates a uniform distribution, which is why I recommended mt_rand.

0
votes

I don't think so.

If you are looking to generate better/faster random numbers in PHP use mt_rand() http://php.net/manual/en/function.mt-rand.php