Math.random () to generate a random integer of a specified range

Source: Internet
Author: User

Math.random () generates a pseudo random number between [0, 1]. Note left and right .

1. The first range, also the most commonly used use, [min, Max], are closed intervals.

For convenience we lift two numbers, [2, 8] between

0____1_____2_____3____4____5____6___7____8_____9____10

1 if we use Math.floor to approximate, we can look like this, take 2 as an example,

The numbers from 2 to 3 range are 2, for example 2.0001, 2.67, 2.9999. If you take 8 as an example,

8.1,8.999 also belong to 8. So we can launch,

Math.floor (Math.random () * (8-2 + 1) + 2);

Since it is rounding down, our step size should need to be plus 1 to get to the number 8 to 9, not including 9

General:

Math.floor (Math.random () * (Max-min + 1) + min)

Let's write a test function to simply verify that the average distribution is met

function random (CNT) {/
    *
        @cnt: [number], need to test the Times
    * *
    var random;
    var result = {};
    for (var i=0 i<cnt; ++i) {
        random = Math.floor (Math.random () * (8-2 + 1) + 2);
        if (random in result) {
            result[random]++;
        } else {
            result[random] = 1;
        }
    } Console.log (result);
    return result;
}

Random (100000);

Test results:

{2:14,395, 3:13,985, 4:14,519, 5:14,425, 6:14,248, 7:14,162, 8:14,266}

is obviously in line with the average distribution.

2) Math.ceil () to simulate,

Math.ceil (Math.random () * (Max-min + 1) + min-1)

3) Math.Round to simulate,

Math.Round (Math.random () * (Max-min + 1) + min-0.5)
2. The other ranges are similar and are not mentioned. Interested in can practice more

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.