JavaScript Math Object

From Techotopia
Revision as of 20:53, 17 May 2007 by Neil (Talk | contribs) (Using JavaScript Math Object and Properties)

Jump to: navigation, search

The JavaScript Math object provides a collections of mathematical constants and methods for performing such tasks as generating random numbers, rounding, obtaining values such as PI and performing calculations.


Contents


JavaScript Math Object Methods

The following table lists the methods available with the Math object:

Method Description
abs Absolute value
sin, cos, tan Standard trigonometric functions; argument in radians
acos, asin, atan, atan2 Inverse trigonometric functions; return values in radians
exp, log Exponential and natural logarithm, base e
ceil Returns least integer greater than or equal to argument
floor Returns greatest integer less than or equal to argument
min, max Returns greater or lesser (respectively) of two arguments
pow Exponential; first argument is base, second is exponent
random Returns a random number between 0 and 1.
round Rounds argument to nearest integer
sqrt Square root

JavaScript Math Object Properties

In addition the math object contains a number of properties for accessing mathematical constants:

Property Description
EEuler's constant
LN2Natural log of 2
LN10Natural log of 10
LOG2ELog base -2 of E
LOG10ELog base -10 of E
PIValue of Pi
SQRT1_2Square root of 0.5
SQRT2Square root of 2

Using JavaScript Math Object and Properties

the first thing to be aware of with the Math object is that an instance of the object already exists. It is not necessary, therefore, to create a new instance using the new keyword. You can simply access the methods and properties by referencing Math.

The methods and properties of the JavaScript Math object can be accessed jsut as with any other objects (see JavaScript Object Basics for more information). For example we can obtain the value of Pi:

Math.Pi;

We can perform square root calculation:

Math.sqrt(3);
<pre>

== Generating Randon Numbers in JavaScript ==

The JavaScript Math object provides the ''random()'' method to generate randon numbers. When developing tyhe ''random()'' method the architects of JavaScript did not know what range you would the use for generation of the randon number. To address this they decided to generate a number between 0 and 1 and then leave you to mulitply it by factors of 10.

To obtain a random number between 0 and 10, for example:

<pre>
var randomNum = Math.random*10;

Rounding and Truncating Numbers withe the Math Object