Is there a way to set a probability control on getting a random value either 1 or 2? Suppose if I want more than 70% of the time it should be 1 and only 30% should be the chance of getting 2 in rand(1,2)
. Is it possible?
Asked
Active
Viewed 984 times
0
-
3Possible duplicate of [Generate random numbers with fix probability](http://stackoverflow.com/questions/21572363/generate-random-numbers-with-fix-probability) – Shogunivar Mar 29 '17 at 11:38
3 Answers
0
Generate a number between 1
and 10
, then if the number is greater than 7, return 2, else return 1
x = rand(1, 10);
if(x > 7){
return 2;
}
else {
return 1;
}
You will have 70% and 30% of chance to get the number you want

Thomas Rbt
- 1,483
- 1
- 13
- 26
0
Why don't you generate a uniformly distributed random number and then filter the number with an if?
int x,r;
r=rand() % 100; // r in the range 0 to 99
if(r<=70){x=1;}
else{x=2;}

Francisco Herrerias-Azcue
- 53
- 1
- 1
- 8
0
This should do the trick:
function yourrand($prob) {
$r = rand();
if ($r < $prob) { return 1; }
else { return 2; }
}

Pedro Cipriano
- 13
- 7