Categories:
Partners

Understanding the two methods of the Math object required to create a random engine

While it is safe for us to ditch the philosopher, it's not exactly wise to do the same with the mathematician. Mathematics play a pivital role in JavaScript when creating a random engine, in the form of the Math object. Don't worry, you don't have to be a math wiz to understand how to create a random engine. Now that we've clarified that, the Math object of JavaScript has many propeties and methods, and we will list them all at the end of this lesson. For now, however, lets simply investigate the two methods neccessary to continue on with our current discussion:

The two methods of the Math object neccessary to create a random engine
Method Description
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.

random()

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:

Math.random()

The first letter of "Math" HAS to be capitalized if you don't want to end up banging your keyword against the desk!

We now know in general how to generate a random number in JavaScript.

round()

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!

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.