Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random float numbers in range PHP

Tags:

php

random

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 )
like image 1000
GGio Avatar asked Dec 09 '22 10:12

GGio


2 Answers

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)));
}
like image 92
Philipp Avatar answered Dec 11 '22 09:12

Philipp


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

like image 44
Lemurr Avatar answered Dec 11 '22 09:12

Lemurr