Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
o increase the ran"e to# sa$# 100# simpl$ chan"e 11 to 101 instead. %ome of $ou ma$ be curious as to wh$ Math.floor()# instead of Math.round()# is used in the above code. &hile both successfull$ round off its containin" parameter to an inte"er within the desi"nated ran"e# Math.floor does so more 'evenl$'# so the resultin" inte"er isn(t lopsided towards either end of the number spectrum. )n other words# a more random number is returned usin" Math.floor(). *$ the wa$# the +andom Motivational script uses ,ust the aforementioned code to randoml$ displa$ a -uote.
Example #. /** * +eturns a random number between min and max */ function "et+andom0rbitar$ (min# max) 1 return Math.random() * (max min) 2 min3 4 /** * +eturns a random inte"er between min and max * 5sin" Math.round() will "ive $ou a non uniform distribution6 */ function "et+andom)nt (min# max) 1 return Math.floor(Math.random() * (max min 2 1)) 2 min3 4
Here's the logic behind it. It's a simple rule of three: returns a 7umber between 0 (inclusive) and 1 (exclusive). o we have an interval li!e this:
Math.random() 80 .................................... 1)
"ow# we'd li!e a number between min (inclusive) and max (exclusive):
80 .................................... 1) 8min .................................. max)
$e can use the Math.random to get the correspondent in the %min# max) interval. &ut# first we should factor a little bit the problem b' subtracting min from the second interval:
80 .................................... 1) 8min min ............................ max min)
(his gives:
80 .................................... 1) 80 .................................... max min)
$e ma' now appl' Math.random and then calculate the correspondent. )et's choose a random number:
Math.random() 9 80 .................................... 1) 80 .................................... max 9 x (what we need)
min)
*on't forget to add min bac!# so that we get a number in the %min# max) interval:
x = Math.random() * (max min) 2 min3
(hat was the first function from +*,. (he second one# returns an integer between min and max# both inclusive. In order to do that# a little tric! is applied. (he second interval is increased to max - 1 exclusive# so that max is a value inside the interval# thus a candidate for the final result:
Math.random() 9 80 .................................... 1) 8min ................................... max) // increase interval 8min ..............................max.. max 2 1) // factor out min 80 ................................max.. max min 2 1) 9 : (what we need)
$hich ma' 'ield max as the value of x. &ut we want an integer# so we use Math.floor:
x = Math.floor(Math.random() * (max min 2 1)) 2 min3