Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to bias random boolean

I'd like to create a random boolean in JavaScript, but I want to take the previous value into account. If the previous value was true, I want it to be more likely for the next value to be true. At the moment I've got this (this is in the context of a closure - goUp and lastGoUp are locals to the containing scope):

function setGoUp() {
    goUp = getRandomBoolean();

    if(lastGoUp) {
        goUp = getRandomBoolean() || goUp;
    }
    else {
        goUp = getRandomBoolean() && goUp;
    }
    lastGoUp = goUp;
}

So, the algorithm goes:

  1. Get a random boolean
  2. If the random boolean from the previous call was True:

    a) get another random boolean, and or these two together

    b) else get another random boolean and and these together.

I'm sure this algorithm could be simplified. I wondered about doing:

if(lastGoUp && goUp) {
    goUp = goUp * (getRandomBoolean() || goUp);
}

but that seems really dirty.

There's also a problem with this algorithm which means that I can only double the chance of getting the same boolean again - I can't tweak it easily. Any ideas?

like image 586
Skilldrick Avatar asked Sep 05 '10 11:09

Skilldrick


2 Answers

Instead of getting a random boolean, get a random number, say between 0 and 99. Keep a threshold value instead of the last number, and adjust the threshold according to the result:

var threshold = 50;

function setGoUp() {
   goUp = getRandomNumber() < threshold;
   threshold += goUp ? -10 : 10;
}

This would keep a running tab, so if you get consecutive results that are the same, the probability would keep falling for that result.

If you only want to consider the last result, you would instead set the threshold to a specific value:

threshold = goUp ? 40 : 60;
like image 39
Guffa Avatar answered Sep 16 '22 15:09

Guffa


You should define the distribution you want, but maybe you are looking for the following?

if (lastGoUp) {
    goUp = Math.random() < 0.8;
} else {
    goUp = Math.random() < 0.2;
}
like image 200
meriton Avatar answered Sep 18 '22 15:09

meriton