Javascript question! math.floor(math.random()) doesn't seem to be that random..?

So for an English project I'm writing a program that randomly generates different examples of certain types of phrases. I'm just about as green as you can get when it comes to programming/coding/scripting/whatever (I had my dad give me a crash course in javascript when I took up this project) and he had me use the statement "(math.floor(math.random()*n)" to generate random numbers. My problem is, when I use this to return a random value of one of my arrays, it just doesn't seem to be that random. So I'm wondering if anyone else has noticed this, if its a known thing, or if I'm just crazy. Either way, I'm looking for a solution. Any help/comments would be appreciated.



Here's just an example of a function that im using to generate a random name from a list.

function getPeople(){return people[Math.floor(Math.random()*38)];}

As you might assume, i have an array of 38 names that it could choose from. However whenever I get an output (Through a series of other functions and stuffs) It seems to have certain favorites that it keeps repeating and not hardly choose from some others. I dunno. It probably is just bad luck :P

2 Answers

  • 8 years ago
    Best Answer

    I ran this little bit of Javascript 4 times:

    var n = 20;

    var i;


        document.write(Math.floor( Math.random()*n) + ' ');

    These were the results:

    1 16 4 6 10 0 17 15 10 11

    1 2 3 10 2 12 0 16 15 8

    17 12 19 6 5 5 2 15 0 14

    1 1 12 1 8 10 16 18 17 8

    Those look random to me. Do they look random to you?

    Note that you need to use Math.floor and Math.random, not math.floor, math.random (upper case M).

    What results are you seeing that make you think it is not random?

    ETA: The JavaScript random number generator is pretty good. Humans have a tendency to see patterns in random numbers (the same way we see animals in random clouds). Like the second line in my output: 1 2 3 doesn't look very random. But it is.

    I suspect that is what you are seeing. Run it a bunch of times, not just a few, and see if you really think it has favorites.

  • Anonymous
    8 years ago

    The numbers generated by what you describe should be random. Did you generate enough examples to be sure it is not random ? Maybe it was just bad luck? :-P

    This code should work to create a random number:

    function getRandomInt (min, max) {

    return Math.floor(Math.random() * (max - min + 1)) + min;


    At least random enough for your needs.

    Did that help ?

Still have questions? Get your answers by asking now.