Random Float Between 0 and 1 in PHP

Random Float between 0 and 1 in PHP

You may use the standard function: lcg_value().

Here's another function given on the rand() docs:

// auxiliary function
// returns random number with flat distribution from 0 to 1
function random_0_1()
{
return (float)rand() / (float)getrandmax();
}

A list of random float number from 0 to 1 using php?

Generate a array of floats, sort with sort(), then reverse the array to give descending order.

So, using your function:

<?php

function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}

$arr = [];
for ($i=0;$i<50;$i++) {
$arr[] = random_from_0_to_1();
}
sort($arr); // sorts ascending
$arr = array_reverse($arr);

var_dump($arr);

Output:

array(50) {
[0]=>
float(0.9991139778863238)
[1]=>
float(0.9733540797482031)
[2]=>
float(0.9620095835821748)
[3]=>
float(0.9390542404442347)
[4]=>
float(0.9368096925023989)
[5]=>
float(0.9321818514411253)
[6]=>
float(0.9321091510039331)
...

Demo: https://3v4l.org/NJvGu

[Edit]

Since you've specifically asked for a version with usort(), try this, which substitutes usort() for sort() and array_reverse():

<?php

function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}

$arr = [];
for ($i=0;$i<50;$i++) {
$arr[] = random_from_0_to_1();
}
usort($arr, function($a,$b){return $b<=>$a;}); // Note parameters reversed in spaceship comparison

var_dump($arr);

Demo: https://3v4l.org/qn7Ka

How to get a random float with x decimal digits in PHP?

Solution Mark Baker suggested is probably the best. Also you don't have to hard-code these big numbers to improve readability:

$min = 0;
$max = 20;
$decimals = 5;

$divisor = pow(10, $decimals);
$randomFloat = mt_rand($min, $max * $divisor) / $divisor;

I just wonder why do you need exactly 5 decimals. If it's just for a presentation, that means you're going to output it as a string, you can use this solution:

$num = $min + lcg_value() * ($max - $min);
$randomFloat = sprintf("%+.5f", $num);

PHP function lgc_value returns random a (pseudo) random float number in the range of (0, 1). Function sprintf returns a string procued according to the format. %+.5f means float number with 5 decimals.

How to convert random integers into float between 0 and 1

You need to divide that random by max value - and max value for such generated bit sequence is 2^length(sequence) (^ her denotes power, **, Math.pow).

For example, if current buffer is "01000100", you need to calculate

68/2^8 = 68/256 = 0.265625  

Random Float against an specific amount with 100 days php

But I want to generate the random numbers in round numbers. Because It
dose not matches the actual amount after generating all the random
numbers if we sum the generated random numbers. Like if I generates
the random numbers for amount of 100, then the sum of all generated
random numbers should 100. This is what actually I want.

What I gathered from your statement is that you want 100 floating numbers with 2 decimal places, and the sum of all these numbers should add up to 100.

This certainly is not the cleanest solution, but here goes:

$total_days = 100;
$total_amount = 100;
$arr = array();

for($i = 0; $i < $total_days; ++$i)
{
$arr[] = rand(0.0, 1000.0);
}
$actual_sum = array_sum($arr);
for($i = 0; $i < $total_days; ++$i)
{
$y = $arr[$i] * ($total_amount /$actual_sum);
$arr[$i] = round($y, 2); //round the numbers to 2 dp. Sum of all numbers could be greater than 100.
}
//hack, logic explained below
$maxElementKeys = array_keys($arr, max($arr)); //get max element's key
unset($arr[$maxElementKeys[0]]); //remove the max element from array, now the array contains 99 elements
$arr = array_values($arr); //rebase the keys

for($i = 0; $i < $total_days; ++$i)
{
if($i < ($total_days - 1) )
$value = $arr[$i];
else
$value = $total_amount - array_sum($arr); //to get the 100th number, subtract from 100 to ensure the total always adds up to 100
$genpackageroi = array(
'userid' => $userid,
'pkgid' => $pkgid,
'pkgcount' => $pkcount,
'amount' => $value,
'created_at' => $created_at,
'updated_at' => $updated_at,
);
DB::table('genpackageroi')->insert($genpackageroi);
}

The logic here is that round all numbers to 2dps. The total of which would in most cases exceed 100 by a few dps.
Next, get the max random number in the array and remove it from the array to make it an array containing 99 elements. The max number is removed to ensure that the sum of the new array stays below well clear of 100. So, to get the 100th element, get the sum of the new array and subtract that value from 100. Now, the total of all elements of the array and the 100th element that was just calculated should add up to exactly 100, with negligible chance for failure.

PHP Random Float Number Generator

You should use mt_srand(microtime()); function only once in your script.

Notice that your code will certainly run quicker than 1 microsecond. Therefore microtime() will return same amount of microseconds and mt_srand will generate the same seed, which will effect in same results from mt_rand.

Try using this code instead:

<?php

function frand($min, $max, $decimals = 0) {
$scale = pow(10, $decimals);
return mt_rand($min * $scale, $max * $scale) / $scale;
}

mt_srand(microtime());
for ($x = 1; $x <= 45; $x++) {
echo frand(1, 17, 8) . "<br/>";
}

?>

PHP How do I rand float value?

From this article:

An elegant way to return random float between two numbers:

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


Related Topics



Leave a reply



Submit