Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain Math.floor(Math.random())

I have seen many places using Math.floor() and Math.random()

like below

$('a.random-color').hover(function() { //mouseover
    var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $(this).animate({
      'color': col,
      'paddingLeft': '20px'
    },1000);
  },function() { //mouseout
    $(this).animate({
      'color': original,
      'paddingLeft': '0'
    },500);
  });
});

Why used Math.floor() and Math.random()?

like image 680
Mr.T.K Avatar asked Dec 20 '11 04:12

Mr.T.K


People also ask

What does the floor () method do?

floor() method rounds a number DOWN to the nearest integer.

What does Math random () * 100 do?

random will not return 1.0 itself, multiplying what Math. random returns with 100 will result in a max value of 99.999.... and when cast to an int turns to 99. Since the randomly generated number is supposed to include 100 you'll have to multiply with 101. Multiplying with 100 will result in a max int value of 99.

What is the formula for Math random?

To create a random decimal number between two values (range), you can use the following formula: Math. random()*(b-a)+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.

What is Math random () in Java?

random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. . When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java. util.


2 Answers

Math.random will give you a floating point number between 0 (inclusive) and 1 (exclusive).

Multiplying that by 256 will give you a number in the range 0 (inclusive) through 256 (exclusive), but still floating point.

Taking the floor of that number will give you an integer between 0 and 255 (both inclusive).

It's the integer from 0 to 255 that you need to construct RGB values like rgb(72,25,183).

like image 72
paxdiablo Avatar answered Sep 19 '22 04:09

paxdiablo


It seems a random color is desired - one with each component random between 0 and 255.

Math.random() returns a random number on [0,1) (ie it may be exactly zero or up to but not including one).

Multiplying that random value by 256 gives a random number on the range [0,256) (ie it may be 255.99, but never 256). Almost there, but not quite.

Math.floor() rounds the number downwards to the nearest whole integer, making the result an integer on [0,255] as desired.

like image 45
Mania Avatar answered Sep 21 '22 04:09

Mania