Louis
Louis

Reputation: 41

PHP Random Probability

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?

Upvotes: 4

Views: 1455

Answers (2)

Tim Seguine
Tim Seguine

Reputation: 2914

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.

Upvotes: 2

user2782001
user2782001

Reputation: 3488

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

Upvotes: 0

Related Questions