Understanding the two methods of the Math object required to create a random engine
|random()||Returns a random number between 0 and 1, although the number returned is usually in between, in the form of 0.xxxxxxxxxxxxxxxxx|
|round(num)||Returns the specified number rounded to the nearest integer.|
Lets break down these methods now.
The random() method of the Math object returns a random number between 0 and 1, although its important to realize that this number is usually in between, (0.xx..., with 17 decimals). The random() method ultilizes the clock in the client's computer to generate this number. Lets see it in action:
<form> <input type="button" value="random number" onClick="alert(Math.random())"> </form>
Click on the above example multiple times; the number alerted will be different each and every time. Notice the syntaz:
The first letter of "Math" HAS to be capitalized if you don't want to end up banging your keyword against the desk!
A random number with 17 decimal points can be quite hard to work with...here's where the round() method comes in. The round() method of the Math object rounds any given number to the nearest interger. Here are a few simple examples:
Math.round(3.4564) //returns 3 Math.round(3.6) //returns 4 Math.round(234.342) //returns 234
We now have all the tools we need to simulate randomness!
- Tutorial introduction
- Understanding the two methods of the Math object required to create a random engine
- Creating a random link out of a specified group of links
- Creating a random link out of all of the links in a document
- Looking at other uses of a random engine- simulating a dice throw + Math object summary