Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining percentage for random number

Tags:

php

My rand(0,1) php function returns me the 0 and 1 randomly when I call it.

Can I define something in php, so that it makes 30% numbers will be 0 and 70% numbers will be 1 for the random calls? Does php have any built in function for this?

like image 571
Sabuj Hassan Avatar asked Oct 20 '25 16:10

Sabuj Hassan


1 Answers

Sure.

 $rand = (float)rand()/(float)getrandmax();
 if ($rand < 0.3)
    $result = 0;
 else
    $result = 1;

You can deal with arbitrary results and weights, too.

 $weights = array(0 => 0.3, 1 => 0.2, 2 => 0.5);
 $rand = (float)rand()/(float)getrandmax();
 foreach ($weights as $value => $weight) {
    if ($rand < $weight) {
       $result = $value;
       break;
    }
    $rand -= $weight;
  }
like image 147
Mark Reed Avatar answered Oct 23 '25 06:10

Mark Reed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!