1
10,000 Loops
Range 0-1
Base Average: 0.5
Base Standard Deviation: 0.288675134595
=======================================

mt_rand()
Average: 0.337839939116
Standard Deviation: 0.264176807272
---

hexdec(sha1(*GUID*))
Average: 0.37834
Standard Deviation: 0.284251515902 <--
---

mt_rand() based from a SET of defined numbers [01234567899]
Average: 0.496042248107 <--
Standard Deviation: 0.321017564651
---

Please could someone help, I cannot seem to find a way to generate RANDOM numbers which complies with a continuous uniform distribution between 0 and 1.

2
  • What kind of output you want to get? Commented Jun 7, 2013 at 14:29
  • 10,000 random numbers between 0 and 1 that outputs an average of 0.5 and that have a standard deviation of 0.288675134595 (1/sqrt(12)) Commented Jun 7, 2013 at 14:43

2 Answers 2

3

According to php-best-random-numbers the mt_rand is the best out of the box PHP method for it.

The problem however is with your very small subset of random numbers. If you generate random between 0 and 1 you will get a very small deviation. So you could increase the numbers when generating the numbers and then devide them by the top number.

Check this codepad for an average of 0.50015533 and a deviation of 0.29015651152368 on my run.

Keep in mind that if you start rounding the values again to get an actual 0 or 1, your standard deviation will be around 0.5.

The code:

<?php
$start = 0;
$top = 10000;
$ar = array();
for ($x=1;$x<=10000;$x++) {
  $val = mt_rand($start, $top) / $top;
  $ar[] = $val;
}

$mean = array_sum($ar) / sizeof($ar);

$devs = array();
foreach($ar as $num) {
    $devs[] = pow($num - $mean, 2);
}

$standard_deviation = sqrt(array_sum($devs) / sizeof($devs));

echo 'Max: ' . max($ar);
echo chr(10);
echo 'Min: ' . min($ar);
echo chr(10);
echo 'Average: ' . $mean;
echo chr(10);
echo 'Deviation: ' . $standard_deviation;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. I did see i had a $start=1, which should be $start=0. Updated now. You could also use a top as mt_getrandmax(). And the manual for mt_getrandmax() also has your random float for best results
2

If you use ModelFactory in Laravel and obtain this error, this solution can be help:

Change

$this->faker->randomNumber(100)

to

$this->faker->numberBetween(1, 100)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.