Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## 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?

• 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!

• 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?

• Sure, the format for a ranged random integer is this
Code:
`var myRand = Math.(Math.random() * (Upper-Lower) + Lower);`
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);```
Code:
```function getRand(l,u) {
return Math.floor(Math.random() * (u-l) + l);
}

var myRand = getRand(563,1224);```

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