71

Possible Duplicate:
Random Float in php

Is it possible to create a random float number between 0 and 1.0 e.g 0.4, 0.8 etc. I used rand but it only accepts integers.

4

7 Answers 7

127
mt_rand() / mt_getrandmax();

Avoid the rand() function, since it usually depends on the platform's C rand() implementation, generally creating numbers with a very simple pattern. See this comment on php.net

Update: In php 7.1 the rand()has been changed and is now merely an alias of mt_rand(). Therefore it is now ok to use rand(), too.

5
  • 25
    or, to more appropriately simulate the 0.0 inclusive to 1.0 exclusive nature of what I consider a standard randomization routine, use mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax() Jan 25, 2013 at 17:53
  • See stackoverflow.com/a/47190869/89818 for a version that supports both the inclusive and the exclusive variant.
    – caw
    Nov 8, 2017 at 22:38
  • 3
    With PHP 7.0 rand use the same generator as mt_rand. However, there is different behavior with the values of the arguments when max is less than min.
    – Rolice
    Jan 8, 2018 at 12:44
  • 1
    lcg_value() does the job. Far simpler. Unfortunately this question is locked and I cannot create an answer with this. (even though this question is far more popular than its counterpart)
    – Lemmings19
    Mar 23, 2022 at 10:07
  • @Lemmings19 lcg_value() is really what I am looking for. But it always returns 0.xxxx. For a more natural result, I do sum it with rand(). lcg_value() + rand() and it will result 1922854540.5079 for example.
    – Dani Fadli
    Jan 31 at 3:16
39

What about simply dividing by 10?

$randomFloat = rand(0, 10) / 10;
var_dump($randomFloat);

//eg. float(0.7)
5
  • 3
    Well it will only be 1 of 10 possible choices, not much room for randomness there
    – Dracony
    Jan 4, 2013 at 10:48
  • 6
    @Dracony The OP only seemed to want 1 decimal. Of course, any number could be picked (rand(0, 10000) / 10000) to cause more decimals and hence more randomness.
    – h2ooooooo
    Jan 4, 2013 at 10:50
  • 7
    @Dracony, h2oooooo: To be pedantic, the amount of randomness doesn't change... Jan 4, 2013 at 10:51
  • @OliCharlesworth Of course you are correct - it's just as random, but has more decimals.
    – h2ooooooo
    Jan 4, 2013 at 10:53
  • @Dracony: ...and now you have my answer :-) stackoverflow.com/questions/14155603/… Feb 16, 2013 at 11:47
14
$v = mt_rand() / mt_getrandmax();

will do that.


In case you want only one decimal place (as in the examples from the question) just round() the value you get...

$v = round( $v, 1 );

...or calculate a number between 0 and 10 and divide by 10:

$v = mt_rand( 0, 10 ) / 10;
6

According to the PHP documentation, if you're using PHP 7 you can generate a cryptographically secure pseudorandom integer using random_int

With that said, here's a function that utilizes this to generate a random float between two numbers:

function random_float($min, $max) {
    return random_int($min, $max - 1) + (random_int(0, PHP_INT_MAX - 1) / PHP_INT_MAX );
}

Although random_int() is more secure than mt_rand(), keep in mind that it's also slower.

A previous version of this answer suggested you use PHP rand(), and had a horrible implementation. I wanted to change my answer without repeating what others had already stated, and now here we are.

2
  • 3
    The result will not be uniformly distributed, since the 1.0 will have a propability of 0.5. Furthermore you'll only get a resolution of 0.1. Jan 4, 2013 at 10:57
  • Took me some time. A few years later. Is this better? Oct 24, 2017 at 22:32
2

how about this simple solution:

abs(1-mt_rand()/mt_rand()) 

or

/**
 * Generate Float Random Number
 *
 * @param float $Min Minimal value
 * @param float $Max Maximal value
 * @param int $round The optional number of decimal digits to round to. default 0 means not round
 * @return float Random float value
 */
function float_rand($Min, $Max, $round=0){
    //validate input
    if ($min>$Max) { $min=$Max; $max=$Min; }
        else { $min=$Min; $max=$Max; }
    $randomfloat = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    if($round>0)
        $randomfloat = round($randomfloat,$round);

    return $randomfloat;
}
4
  • 2
    When using other people's work, please always reference your sources. ivankristianto.com/… Thanks!
    – Pekka
    Dec 3, 2013 at 22:52
  • 1
    There is an error in the code: These line: if ( $min >$Max) { $min=$Max; $max=$Min; } Should be : if ( $Min >$Max) { $min=$Max; $max=$Min; }
    – Madcoe
    Feb 5, 2014 at 7:39
  • Also, there is no need to guarantee that $Min < $Max—having them swapped yields a mathematically identical probability distribution…
    – Jollywatt
    Dec 15, 2015 at 2:47
  • 2
    The first solution is not valid. Dividing two independent uniformly distributed random variables will get you a Uniform Ratio distribution (although computers are always discrete; this is an approximation). See en.wikipedia.org/wiki/Ratio_distribution. There's a probability of 1/4 that it will return a number larger than one (and can return numbers of any size with probability decreasing as the square of the number). The uniform ratio distribution is no longer uniformly distributed.
    – aphid
    May 17, 2017 at 14:55
2

Try this

// Generates and prints 100 random number between 0.0 and 1.0 
$max = 1.0;
$min = 0.0;
for ($i = 0; $i < 100; ++$i)
{
    print ("<br>");
    $range = $max - $min;
    $num = $min + $range * (mt_rand() / mt_getrandmax());    
    $num = round($num, 2);
    print ((float) $num);
}
1

Cast to float* and divide by getrandmax().


* It seems that the cast is unnecessary in PHP's arbitrary type-juggling rules. It would be in other languages, though.

2
  • 3
    The rules aren't arbitrary. Jun 12, 2014 at 18:28
  • 3
    @Fuser97381: Maybe not arbitrary, but certainly built up as a series of ad-hoc afterthoughts, resulting in a nasty, inconsistent set of rules. Jun 12, 2014 at 18:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.