Page 1 of 1

[solved] Random numbers?

Posted: Tue Jan 13, 2009 12:06 pm
by Chalks
I was looking at the source of a website I wrote awhile ago and I think I might have made a mistake. I'm not sure though because Javascript isn't really my strong suit.

Code: Select all

function genrand(maxnum) {
  var randnum=Math.floor(Math.random()*maxnum);
  return randnum;
}
 
function gennew(length) {  // length is the length of an array
  var currloc = genrand(length);
//...
I'm trying to generate a random number within my array's index bounds. It works, but I don't think it's actually random. Can someone explain a better way to do this to me?

Re: Random numbers?

Posted: Tue Jan 13, 2009 12:14 pm
by Apollo
Your genrand(maxnum) function returns random numbers from 0 up to (and including) maxnum-1. It will never return maxnum.

Re: Random numbers?

Posted: Tue Jan 13, 2009 12:21 pm
by Chalks
that's what it should do. Also, next time I'll google first... my math was wrong. Using ciel or round would have screwed me up, but using Math.floor actually _does_ do exactly what I want. I thought it weighted certain numbers more heavily but it doesn't.