GGio
GGio

Reputation: 7653

Generate random float numbers in range PHP

I have a code that initializes a dice object by the following code:

public function initializeDiceSides($totalSides, $fair, $maxProbability = 100) {
   $maxTemp = $maxProbability;
   $sides = array();

   for ($side = 0; $side < $totalSides; $side++) {
     //if we want fair dice just generate same probabilities for each side
     if ($fair === true) {
       $probability = number_format($maxProbability/$totalSides, 5);
     } else {
       //set probability to random number between 1 and half of $maxTemp
       $probability = number_format(mt_rand(1, $maxTemp/2), 5);

       //subtract probability of current side from maxtemp
       $maxTemp= $maxTemp- $probability;

       $sides[$side] = $probability;
     }
   }

   echo $total . '<br />';
   print_r($sides);
}

above code prints:

89
Array ( [0] => 48.00000 [1] => 13.00000 [2] => 14.00000 
        [3] => 9.00000 [4] => 2.00000 [5] => 2.00000 )

I want to be able to generate float numbers instead of integers, I want to have something like

Array ( [0] => 48.051212 [1] => 13.661212 [2] => 14.00031 
        [3] => 9.156212 [4] => 2.061512 [5] => 2.00000 )

Upvotes: 5

Views: 8012

Answers (5)

IMSoP
IMSoP

Reputation: 97688

As of PHP 8.3, there is a built-in method for this, Random\Randomizer::getFloat.

The simplest usage looks like this:

$randomizer = new \Random\Randomizer();
$probability = $randomizer->getFloat(1, $maxTemp/2);

There are then two things you can tweak to your needs:

  • By default, the value returned is greater than or equal to the minimum, and strictly less than the maximum, referred to as IntervalBoundary::ClosedOpen. You can choose any combination of "closed" and "open" that suits your needs (see the manual page for some examples).
  • The Randomizer is an object so that you can initialize it with different "engines". By default, it uses a cryptographically secure source of true randomness; but if you want reproducible results, based on some seed, you can use one of the other classes in the Random\Engine namespace.

Upvotes: 0

caw
caw

Reputation: 31489

function random_float($min = 0, $max = 1, $includeMax = false) {
    return $min + \mt_rand(0, (\mt_getrandmax() - ($includeMax ? 0 : 1))) / \mt_getrandmax() * ($max - $min);
}

Upvotes: 1

grub
grub

Reputation: 41

You could multiply the variables that you feed into mt_random by a factor of, say, 100000, and then divide the output by the same factor to get a float value.

Upvotes: 1

Philipp
Philipp

Reputation: 15629

A simple approach would be to use lcg_value and multiply with the range and add the min value

function random_float ($min,$max) {
    return ($min + lcg_value()*(abs($max - $min)));
}

Upvotes: 11

Lemur
Lemur

Reputation: 2665

I'd just generate random numbers from 0 to 999999 and then divide them by 100000

Upvotes: 2

Related Questions