简体   繁体   中英

using Javascript to get random number between 2 numbers but with a specific range less likely

Im using a random number function to get two random numbers between 219 and 1500. This works as expected but id like for numbers between 1200 and 1500 to be 50% less likely to occur. How can I achieve this?

I did try searching first but there is so much out there about random numbers that its difficult to find anything relevant to my issue.

 function getRandomBase (min, max) {


    orBase = Math.floor(Math.random() * (max - min + 1)) + min; 
    document.getElementById("box1").value = orBase;

    newBase = Math.floor(Math.random() * (max - min + 1)) + min; 
    document.getElementById("box3").value = newBase;


}

Demo

I would try something like this:

function number() {
    var isLower = (Math.random() * 3) < 2;
    if(isLower) {
        return randomNumber(219,1199);
    } else {
        return randomNumber(1200,1500);
    }
}

function randomNumber(min,max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Updated fiddle: http://jsfiddle.net/pH3ZW/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM