Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a truly inclusive random method for javascript

Tags:

Javascript's MATH object has a random method that returns from the set [0,1) 0 inclusive, 1 exclusive. Is there a way to return a truly random method that includes 1.

e.g.

var rand = MATH.random()*2;  if(rand > 1) {    rand = MATH.floor(rand); }  return rand;  

While this always returns a number from the set [0,1] it is not truly random.

like image 261
Adrian Adkison Avatar asked Jan 27 '10 00:01

Adrian Adkison


1 Answers

This will return [0,1] inclusive:

if(MATH.random() == 0)     return 1; else     return MATH.random(); 

Explanation: If the first call to random() returns 0, return 1. Otherwise, call random again, which will be [0,1). Therefore, it will return [0,1] all inclusive.

like image 129
Trevor Avatar answered Sep 19 '22 13:09

Trevor