[solved] Random numbers?

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

[solved] Random numbers?

Post 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?
Last edited by Chalks on Tue Jan 13, 2009 12:22 pm, edited 1 time in total.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Random numbers?

Post by Apollo »

Your genrand(maxnum) function returns random numbers from 0 up to (and including) maxnum-1. It will never return maxnum.
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

Re: Random numbers?

Post 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.
Post Reply