Random Numbers in JavaScript

Our random number generation example demonstrates how to generate pseudorandom numbers in JavaScript.

// In JavaScript, we use the Math.random() function to generate random numbers

function main() {
    // Math.random() returns a float between 0 (inclusive) and 1 (exclusive)
    // To get an integer between 0 and 99:
    console.log(Math.floor(Math.random() * 100) + "," + 
                Math.floor(Math.random() * 100));

    // Math.random() directly gives a float between 0 and 1
    console.log(Math.random());

    // To get a float between 5 and 10:
    console.log((Math.random() * 5 + 5) + "," +
                (Math.random() * 5 + 5));

    // For reproducible random numbers, we can use a seeded random number generator
    // Here's a simple implementation of a seeded random number generator
    function seededRandom(seed) {
        let x = Math.sin(seed++) * 10000;
        return x - Math.floor(x);
    }

    let seed = 42;
    console.log(Math.floor(seededRandom(seed) * 100) + "," +
                Math.floor(seededRandom(seed + 1) * 100));

    // Using the same seed will produce the same sequence
    seed = 42;
    console.log(Math.floor(seededRandom(seed) * 100) + "," +
                Math.floor(seededRandom(seed + 1) * 100));
}

main();

You can run this script using Node.js:

$ node random-numbers.js
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Note that the built-in Math.random() in JavaScript doesn’t support seeding. For more advanced random number generation with seeding capabilities, you might want to use a library like seedrandom.

JavaScript’s Math object provides other methods for random number operations, such as Math.round(), Math.ceil(), and Math.floor() which can be useful when working with random numbers.

查看推荐产品

Comments powered by Disqus