Simulating events with different probabilities

suggest change

Sometimes you may only need to simulate an event with two outcomes, maybe with different probabilities, but you may find yourself in a situation that calls for many possible outcomes with different probabilities. Let’s imagine you want to simulate an event that has six equally probable outcomes. This is quite simple.

function simulateEvent(numEvents) {
    const event = Math.floor(numEvents*Math.random());
    return event;
}

// simulate fair die
console.log("Rolled a "+(simulateEvent(6)+1));  // for example, "Rolled a 2"

However, you may not want equally probable outcomes. Say you had a list of three outcomes represented as an array of probabilities in percents or multiples of likelihood. Such an example might be a weighted die. You could rewrite the previous function to simulate such an event.

function simulateEvent(chances) {
    let sum = 0;
    chances.forEach(function(chance) {
        sum+=chance;
    });
    const rand = Math.random();
    let chance = 0;
    for(let i=0; i<chances.length; i++) {
        chance+=chances[i]/sum;
        if(rand<chance) {
            return i;
        }
    }
    
    // Reached when every weight is 0, a weight is negative,
    // or rounding leaves the running total a hair under 1.
    return -1;
}

// simulate weighted dice where 6 is twice as likely as any other face
// using multiples of likelihood
console.log("Rolled a "+(simulateEvent([1,1,1,1,1,2])+1));  // for example, "Rolled a 1"

// using probabilities
console.log("Rolled a "+(simulateEvent([1/7,1/7,1/7,1/7,1/7,2/7])+1));  // for example, "Rolled a 6"

As you probably noticed, these functions return an index, so you could have more descriptive outcomes stored in an array. Here’s an example.

const rewards = ["gold coin","silver coin","diamond","god sword"];
const likelihoods = [5,9,1,0];
// least likely to get a god sword (0/15 = 0%, never),
// most likely to get a silver coin (9/15 = 60%, more than half the time)

// simulate event, log reward
console.log("You get a "+rewards[simulateEvent(likelihoods)]);  // for example, "You get a silver coin"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents