Technology Programming

JavaScript By Example

The Math object is rather different from all the other objects built into JavaScript because it is intended to be used directly rather than as the basis for your own objects. You would never define anything as new Math() because you can just use the supplied Math object itself to provide all of the advanced mathematical functionality that the object provides.

The Math object provides properties that are predefined to contain specific values that are useful for advanced mathematical processing such as pi, e, and the square root of 2.

The methods can be divided into two groups - those such as ceil(), floor(), abs() and max() which are frequently used with numbers to convert numbers to integers, remove negative signs, or to find the biggest or smallest of several numbers and the other group of methods such as sin(), atan(), log() and pow() which provide the more advanced maths functionality to go with the properties.

In this example we look at how we can use a couple of the Math methods to produce the equivalent of a die roll and get a random number between one and siix. The Math.random() method returns a random number that is greater or equal to zero and less than one. Once we multiply that by six and discard the decimal portion (which is what Math.floor() does) we then have an integer between 0 and 5 inclusive. We then just need to add one to get a number between 1 and 6 inclusive. We can't use Math.ceil instead of Math.floor in order to avoid adding the one as that would give an invalid result if the random number were exactly equal to zero.

var die;
die = Math.floor(Math.random()*6)+1;

Related posts "Technology : Programming"

How LiteData Creates Better Sites For Their Clients

Programming

Contrastive analysis of methodologies of test design for functional testing

Programming

A Proper Diet That Is Filled With Healthy Fats Can Help You Lose Weight

Programming

How to Create an Array of Objects in PHP

Programming

How to read character information from the World of Warcraft servers.

Programming

7 Ways To Master Ayurvedic Medicine For Constipation Without Breaking A Sweat

Programming

Web Design Company Kolkata for Seamless Ecommerce Site

Programming

What Happened to "Borland Delphi"? What is CodeGear? What is Embarcadero?

Programming

How to Send Pages to iFrame

Programming

Leave a Comment