Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    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?

  • #2
    Senior Coder
    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() * (10-5) + 5);

    Thats it!

  • #3
    Regular Coder
    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?

  • #4
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Sure, the format for a ranged random integer is this
    Code:
    var myRand = Math.(Math.random() * (Upper-Lower) + Lower);
    Soo, for your two examples...
    Code:
    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
    Code:
    var upper = 46;
    var lower = 22;
    var myRand = Math.(Math.random() * (upper-lower) + lower);
    Which could lead to your own random number function!
    Code:
    function getRand(l,u) {
    	return Math.floor(Math.random() * (u-l) + l);
    	}
    
    var myRand = getRand(563,1224);

  • #5
    Regular Coder
    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*


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •