JRS: In article <bu*********@drn.newsguy.com>, seen in
news:comp.lang.javascript, Lee <RE**************@cox.net> posted at Thu,
15 Jan 2004 12:08:16 :-
The correct way to generate a "random" integer is described at:
http://www.jibbering.com/faq/#FAQ4_22
According to someone trustworthy, that method is not entirely reliable.
From a linked page :
Opera (5.02..6.01 at least), I have read, can give a value of 1.0
from its Math.random(), with a frequency of the order of one
in 35000 times - so that the function Random() below can
return N. There is a
<http://homepage.ntlworld.com/stephen.chalmers/op6/random1.htm> Test
age by SC. Precautions are needed; appending %1 to Math.random()
should do. LRN 20030804 : Opera 4, 5, not 6.05.
Sometimes, returning N may not much matter; other times, it may cause
the page logic to fail, resulting in error but not necessarily obvious
error.
I do not know which values in 0..N-1 that 1/35000 probability is
extracted from (it is transferred to 0, of course, by %1). If a 1/35000
non-uniformity matters, ISTM that one should perhaps be using a better
algorithm and maybe another language.
function Random(N) {
do { T = Math.random() } while (T>=1.0) ; return Math.floor(N*T) }
may be better than
function Random(N) { return Math.floor(N*(Math.random()%1)) }
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.