View Full Version : Random Variable...?

Eternity Angel

08-23-2002, 03:46 PM

Amazingly enough, I've never come across how to make a random number!

I did see some random quote thingie... But I do not understand "Math.random()"...

How do you make one?

beetle

08-23-2002, 03:57 PM

Math.random will generate a random decimal (or float) somewhere between 0 and 1. The most common way to convert this decimal into an integer is by using Math.floor(x) (retrieves the closest integer to x, but not greater than x) But, before we can use Math.floor(), we need to put our decimal into a usable range, which is handled by simple multplication. Lets say we want a randum integer between 0 and 10;

var myRand = Math.floor(Math.random() *10);

There! Now, if you want a more specific range, say between 5 and 10, you will need this extra arithmetic

var myRand = Math.floor(Math.random() * (10-5) + 5);

Thats it!

Eternity Angel

08-23-2002, 04:16 PM

Thank you.

Although, I still don't understand it quite...

Can you give me a few more examples, like, say I wanted a random number between 22 and 46, or 563 and 1224?

beetle

08-23-2002, 04:25 PM

Sure, the format for a ranged random integer is this

var myRand = Math.(Math.random() * (Upper-Lower) + Lower);Soo, for your two examples...

var myRand = Math.floor(Math.random() * (46-22) + 22);

var myRand = Math.floor(Math.random() * (1224-563) + 563);Or, it could be done with variables

var upper = 46;

var lower = 22;

var myRand = Math.(Math.random() * (upper-lower) + lower);Which could lead to your own random number function!

function getRand(l,u) {

return Math.floor(Math.random() * (u-l) + l);

}

var myRand = getRand(563,1224);

Eternity Angel

08-23-2002, 04:36 PM

Thank you, once again!

It's all starting to make some sort of weird sense...!

*Goes off to write this information down*

Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.