The Math object is used as a namespace for several math functions. This chapter provides an overview.
The properties of Math are as follows:
Math.E
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Math.PI
Math.SQRT1_2
Math.SQRT2
The numerical functions of Math include the following:
Math.abs(x)
x.
Math.ceil(x)
Returns the smallest integer ≥ x:
> Math.ceil(3.999) 4 > Math.ceil(3.001) 4 > Math.ceil(-3.001) -3 > Math.ceil(3.000) 3
For more on converting floating-point numbers to integers, see Converting to Integer.
Math.exp(x)
Math.E). This is the inverse of Math.log().
Math.floor(x)
Returns the largest integer ≤ x:
> Math.floor(3.999) 3 > Math.floor(3.001) 3 > Math.floor(-3.001) -4 > Math.floor(3.000) 3
For more on converting floating-point numbers to integers, see Converting to Integer.
Math.log(x)
x) of x. This is the inverse of Math.exp().
Math.pow(x, y)
Returns xy, x raised to the power of y:
> Math.pow(9, 2) 81 > Math.pow(36, 0.5) 6
Math.round(x)
Returns x rounded to the nearest integer (the greater one if it is between two integers):
> Math.round(3.999) 4 > Math.round(3.001) 3 > Math.round(3.5) 4 > Math.round(-3.5) -3
For more on converting floating-point numbers to integers, see Converting to Integer.
Math.sqrt(x)
Returns
, the square root of x:
> Math.sqrt(256) 16
The trigonometric methods accept and return angles as radians. The following functions show you how you could implement conversions, should you need to:
From degrees to radians:
functiontoRadians(degrees){returndegrees/180*Math.PI;}
Here is the interaction:
> toRadians(180) 3.141592653589793 > toRadians(90) 1.5707963267948966
From radians to degrees:
functiontoDegrees(radians){returnradians/Math.PI*180;}
Here is the interaction:
> toDegrees(Math.PI * 2) 360 > toDegrees(Math.PI) 180
The trigonometric methods are as follows:
Math.acos(x)
x.
Math.asin(x)
x.
Math.atan(x)
x.
Math.atan2(y, x)
Math.cos(x)
x.
Math.sin(x)
x.
Math.tan(x)
x.
Following are the remaining Math functions:
Math.min(x1?, x2?, ...)
Returns the smallest number among the parameters:
> Math.min() Infinity > Math.min(27) 27 > Math.min(27, -38) -38 > Math.min(27, -38, -43) -43
Use it on arrays via apply() (see func.apply(thisValue, argArray)):
> Math.min.apply(null, [27, -38, -43]) -43
Math.max(x1?, x2?, ...)
Returns the largest number among the parameters:
> Math.max() -Infinity > Math.max(7) 7 > Math.max(7, 10) 10 > Math.max(7, 10, -333) 10
Use it on arrays via apply() (see func.apply(thisValue, argArray)):
> Math.max.apply(null, [7, 10, -333]) 10
Math.random()
Returns a pseudorandom number r, 0 ≤ r < 1.
The following function uses Math.random() to compute a random integer:
/*** Compute a random integer within the given range.** @param [lower] Optional lower bound. Default: zero.* @returns A random integer i, lower ≤ i < upper*/functiongetRandomInteger(lower,upper){if(arguments.length===1){upper=lower;lower=0;}returnMath.floor(Math.random()*(upper-lower))+lower;}