Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 5 of 5
Thread: Random Variable...?

08232002, 02:46 PM #1
 Join Date
 Jul 2002
 Location
 Canada, eh?
 Posts
 133
 Thanks
 2
 Thanked 3 Times in 3 Posts
Random Variable...?
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?
08232002, 02:57 PM
#2
 Join Date
 Aug 2002
 Posts
 3,467
 Thanks
 0
 Thanked 0 Times in 0 Posts
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() * (105) + 5);
Thats it!
08232002, 03:16 PM
#3
 Join Date
 Jul 2002
 Location
 Canada, eh?
 Posts
 133
 Thanks
 2
 Thanked 3 Times in 3 Posts
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?
08232002, 03:25 PM
#4
 Join Date
 Aug 2002
 Posts
 3,467
 Thanks
 0
 Thanked 0 Times in 0 Posts
Sure, the format for a ranged random integer is thisSoo, for your two examples...Code:var myRand = Math.(Math.random() * (UpperLower) + Lower);Or, it could be done with variablesCode:var myRand = Math.floor(Math.random() * (4622) + 22); var myRand = Math.floor(Math.random() * (1224563) + 563);Which could lead to your own random number function!Code:var upper = 46; var lower = 22; var myRand = Math.(Math.random() * (upperlower) + lower);Code:function getRand(l,u) { return Math.floor(Math.random() * (ul) + l); } var myRand = getRand(563,1224);
08232002, 03:36 PM
#5
 Join Date
 Jul 2002
 Location
 Canada, eh?
 Posts
 133
 Thanks
 2
 Thanked 3 Times in 3 Posts
Thank you, once again!
It's all starting to make some sort of weird sense...!
*Goes off to write this information down*