search

Home  >  Q&A  >  body text

javascript - How to get a random number in a symmetric range in JS?

For example, I want to use Math.random() to get random numbers in the ranges of -20~-10 and 10~20. Is there any most streamlined solution? For example, can it be done without an if statement? Thank you all for clearing up the confusion.

淡淡烟草味淡淡烟草味2700 days ago809

reply all(4)I'll reply

  • phpcn_u1582

    phpcn_u15822017-07-05 10:46:41

    (Math.floor(Math.random() * (20 - 10 + 1)) + 10) * (Math.random() < 0.5 ? -1 : 1)

    reply
    0
  • 某草草

    某草草2017-07-05 10:46:41

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

    reply
    0
  • 为情所困

    为情所困2017-07-05 10:46:41

    Math.random() * (max - min) + min;

    See details


    Modification:

    (Math.random() * (max - min) + min)*(Math.random()<0.5?1:-1);
    

    reply
    0
  • 欧阳克

    欧阳克2017-07-05 10:46:41

    function rand(min, max) {
        if ( min >= max ) {
            return;
        }
        return  Math.floor(min + (max - min+1) * Math.random());
    }

    This is to take an integer within a range

    reply
    0
  • Cancelreply