Generate random float numbers in range PHP

前端 未结 5 1783
夕颜
夕颜 2020-12-18 09:38

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

public function initializeDiceSides($totalSides, $fair, $maxProbability = 100) {
   $maxT         


        
相关标签:
5条回答
  • 2020-12-18 09:59

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

    0 讨论(0)
  • 2020-12-18 10:00

    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.

    0 讨论(0)
  • 2020-12-18 10:06
    function random_float($min = 0, $max = 1, $includeMax = false) {
        return $min + \mt_rand(0, (\mt_getrandmax() - ($includeMax ? 0 : 1))) / \mt_getrandmax() * ($max - $min);
    }
    
    0 讨论(0)
  • 2020-12-18 10:11

    Make sure the value of $maxProbability and $totalSides are floats.
    If they are integers, the result will be typed as an integer.

    0 讨论(0)
  • 2020-12-18 10:15

    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)));
    }
    
    0 讨论(0)
提交回复
热议问题