Search code examples
javascriptnode.jsrandomweighted

JavaScript weighted random or percent of the time


I have a Node.js process (setInterval) that runs every 100ms. I have certain actions that I want to take every x period of time. So for example, 2% of the time do X, 10% of the time do Y, etc.

Right now, I'm basically doing it like this:

var rand = Math.floor(Math.random() * (1000 + 1));

if(rand > 900) {  // Do something }

if(rand > 950) {  // Do something }

The problem is it's very inconsistent. You would want if(rand > 900) to be at least close to 10% of the time, but sometimes it may be 10x in a row or not at all.

Would anyone have suggestions to a better solution that would be more accurate if we assume the 100ms interval is fixed.

Thank you!

Edit: Based on Dr. Dredel's comments:

var count = 0;
setInterval(function(){

    if(count++ % 4 == 0) {
       console.log('25% of the time');
    }

}, 100);​

Solution

  • If your interval is fixed, I would round your stamp to the nearest hundred and then use those segments that relate to your needs... 100 and 200 but not 300- 1000 to represent 2%.

    If you CAN use a counter, then that's the more obvious way to do it.

    if(myCounter++ % 4 == 0)
        //this happens 25 percent of the time 
    

    As Emil points out, probability is not the correct approach here, and I don't get the sense that you're married to it... It sounds like you're using it because you didn't see a better way to provoke something to happen x% of the time. If we're misunderstanding you, you need to explain in better detail why you're using odds here.