Jump to content
Sign in to follow this  
RAZZ

A good random function

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 :)

Share this post


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))

Share this post


Link to post
Share on other sites

Yeah, OK. But does each number have an equal chance of coming up?-And what if I want 0-333, can I just do

Math.floor(Math.random()*334)

?...And thanks for answering!

Share this post


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 :)

Share this post


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!

Share this post


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 =]

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...