Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

seed random number generator?

Status
Not open for further replies.

Magnificat

Technical User
Apr 17, 2001
38
0
0
US
Is it possible to seed a random number generator in JavaScript (so that, say, you can generate a seed from the date so that the results from the generator are the same on any given day)? I've tried putting the seed as a parameter in the Math.random() function, but that gets me nowhere. I realize that people have written random number generators that can be seeded, and I could probably fix up something of my own, but I'd rather not have to stick in a bunch of code just to generate a random number. So is there any way to provide a seed for a function such as Math.random()?
 
I think this is what you're looking for? A floating number is generated between 1 & 0 (eg 0.502) and stored in the variable rnd. It's then multiplied by 10 (5.02) and rounded down to give 5 stored in variable num.

Obviously thi'll only generate a number between 1 & 10, but you could multiply it by 100 to give you a value between 1 & 100.

I just used the document.write as an example, obviously you'll be using the number differently.


<HEAD>
<SCRIPT>

function random()
{


// Declare Variables //
var rnd;
var num;


// Generate Random Number //
rnd = Math.random();


// Multiply by 10 //
num = Math.floor(rnd * 10) +1;


document.write(num);
}

</SCRIPT>
</HEAD>
<BODY onLoad=&quot;random();&quot;>

</BODY>

I hope this is what you were looking for?

 
Well, not really. What I want is to be able to seed the function so that it generates the same random numbers whenever I give it the same seed. Obviously, I can write my own randomizer function or use someone else's, but I was hoping to use a &quot;stock&quot; function like Math.random(). Your function appears to just generate a random number without permitting explicit seeding.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top