Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random boolean 70% True, 30% false

I have the following function that generates a random boolean. choose_direction: function () {

 var random_boolean = Math.random() >= 0.5;
    if (random_boolean) {
        trade.call()
        prev_trade.goingUp = true
        console.log('Trade: CALL!!!!!!!!!!!!!!!!!!!!!!')
    } else {
        trade.put()
        prev_trade.goingUp = false
        console.log('Trade: PUT!!!!!!!!!!!!!!!!!!!!!!!!')
    }
}

However, I need the distribution to be unfair. More specifically, I want the output to be 70% of the time true and 30% of the time false.

like image 709
TSR Avatar asked May 30 '17 13:05

TSR


1 Answers

Instead of >= 0.5 you just need < 0.7:

var random_boolean = Math.random() < 0.7;
// 70% this will be true, 30% false

As @plasmacel commented, Math.random() returns a value between 0 and 1 (including 0, but not 1: [0, 1)), so therefore we do < 0.7.

like image 79
Ionică Bizău Avatar answered Nov 08 '22 00:11

Ionică Bizău