Jump to content

A good random function


RAZZ

Recommended Posts

Hi,I am having trouble working with the built-in math.random() function.What I need is a function that can return a good random number between two set values, or just 0 and a set value.So.. Does anyone have one?This 0-1 stuff is really confusing me.Thanks!/EDITOk, so now I have some code to go with the post. I would really appreciate some oppinions on weather or not this function will return "good" random numbers, and why - or why not.

function rand(value){	return Math.round( Math.random()*100000 )%value;}

Let the discussions begin..... Whadda ya say :)

Link to post
Share on other sites

This will produce a random number between 0 and 10, use an alert to check values if you are unsure.

alert(Math.floor(Math.random()*11))

Link to post
Share on other sites
Yeah, OK. But does each number have an equal chance of coming up?

Yes they all have an equal chance, but i would say if you were to refresh the page 10 times the chances of every number showing at least once would be slim, but possible. :)
And what if I want 0-333, can I just do
Math.floor(Math.random()*334)

?

Correct :)
Link to post
Share on other sites
Yes they all have an equal chance, but...
OK, I will trust you on that, for now... :):) But I think I will have to test it some time. Then I will be shure to report back with my findings.Thanks again!
Link to post
Share on other sites

Well, since you can only set one number, and the other number is always 0, I wouldnt like that very much. Heres a function one where you set the min #(num1) and the max #(num2):

function randomnumber(num1, num2){	num1 = parseInt(num1);	num2 = parseInt(num2);  var generator = Math.random()*(num2-num1);  generator = Math.round(num1+generator);  document.test.result.value = generator;}

heres and example:

randomnumber(5000, 5050);

that would produce a number inbetween those..hope you like this one =]

Link to post
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...