Jump to content

Adding a data with Probability K.


haku87

Recommended Posts

Sorry, I has this problem with probability adding.

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?

Link to comment
Share on other sites

<?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.

Link to comment
Share on other sites

<?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;
}
?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.