Skip to content
Advertisement

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

I want to create a function to print a list of 50 random floats from 0 to 1.

The function to print one random float is simply :

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

But how do I get a list of 50 numbers in descending order?

I want to use usort() function, but I am not sure how to use it with a list of 50 random floats.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement