Jump to content

Adding a data with Probability K.


haku87

Recommended Posts

<?php
function addX() {
  $rand = rand(1,5);
  if ($rand == 1) { return true; } else { return false; }
}
?>

Is that what you meant? This will generate a random number, giving it a probability of 0.2(20%) to be true, 80% chance to be false.

<?php
function addX() {
  $rand = rand(1,5);
  if ($rand == 1) { return true; } else { return false; }
}
?>

Is that what you meant? This will generate a random number, giving it a probability of 0.2(20%) to be true, 80% chance to be false.

You could shorten that, just to make it look a little nicer:

 

<?php
function addX() {
  return (rand(1, 5) == 1) ? true : false;
}
?>

You could shorten that, just to make it look a little nicer:

 

This is a shorter example, but he is learning and it's best to understand how the method works before working on shorthand logic for this.. It will not be as easy to understand for a beginner.

Let say every time i called a function AddX(), it return a true or false. With a probability of 0.2,

Every 5 time that I called this function Add(X), 1 time it will return me true and 4 time false. How to do that?

 

Well which is it?  Do you want it to return true 20% of the time and false 80% of the time?  Or out of 5 calls do you want it to return true at least once without knowing which of the 5 calls it will be?  Because they are not the same thing.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.