Programming Tutorials

Math object and Math functions in Javascript

By: Nicholas C. Zakas in Javascript Tutorials on 2008-08-16  

The Math object is the built-in object that you wish you had during those high school math classes: It knows all the formulas for the most complicated mathematical problems, and it can figure them out for you if you give it the numbers to work with. The Math object has several properties, consisting mostly of special values in the world of mathematics.

The following table describes these properties:

Property Description
E The value of e, the base of the natural logarithms.
LN10 The natural logarithm of 10.
LN2 The natural logarithm of 2.
LOG2E The base 2 logarithm of E.
LOG10E The base 1 logarithm of E.
PI The value of π.
SQRT1_2 The square root of 1⁄2.
SQRT2  The square root of 2.

Although the meanings and uses of these values is outside the scope of this book, if you know what they are, they are available when you need them. The Math object also contains many methods aimed at performing both simple and complex mathematical calculations.

The methods min() and max() are used to determine which number is the lowest or highest in a group of numbers. Each of these methods accepts any number of parameters:

var iMax = Math.max(3, 54, 32, 16);
alert(iMax); //outputs "54"
var iMin = Math.min(3, 54, 32, 16);
alert(iMin); //outputs "3"

Out of the number 3, 54, 32, and 16, max() returns the number 54 whereas min() returns the number 3. These methods are useful to avoid extra loops and if statements to determine the maximum value out of a group of numbers. Another method is abs(), which returns the absolute value of a number. The absolute value is the positive version of a negative number (positive numbers are their own absolute values).

var iNegOne = Math.abs(-1);
alert(iNegOne); //outputs "1"
var iPosOne = Math.abs(1);
alert(iPosOne); //outputs "1"

In this example, abs(-1) returns 1 and so does abs(1).

The next group of methods has to do with rounding decimal values into integers. Three methods, ceil(), floor(), and round(), handle rounding in different ways.

  • The ceil() method represents the ceiling function, which always rounds numbers up to the nearest value.

  • The floor() method represents the floor function, which always rounds numbers down to the nearest value.

  • The round() method represents a standard round function, which rounds up if the number is more than halfway to the next value (0.5 of the way there) and rounds down if not. This is the way you were taught to round in elementary school.

To illustrate how each of these methods works, consider using the value 25.5:

alert(Math.ceil(25.5)); //outputs "26"
alert(Math.round(25.5)); //outputs "26"
alert(Math.floor(25.5)); //outputs "25"

For ceil() and round(), passing in 25.5 returns 26, whereas floor() returns 25. Be careful not to use these methods interchangeably because you could end up with some unexpected results. Another group of methods relates to the use of exponents. These methods include the following: exp(), which raises Math.E to a given power; log(), which returns the natural logarithm of a particular number; pow(), which raises a given number to a given power; and sqrt(), which returns the square root of a given number.

Essentially, exp() and log() reverse each other, whereas exp() raises Math.E to a specific power and log() determines what exponent of Math.E is needed to equal the given value. For example:

var iNum = Math.log(Math.exp(10));
alert(iNum);

Here, Math.E is first raised to the power of 10 by using exp(), and then log() returns 10 as the exponent necessary to equal that number. If you are confused, you're not alone. This type of stuff stumps high school and college math students worldwide. Chances are if you don't know what the natural logarithm is, you'll probably never need to code it.

The pow() method is used to raise a number to a given power, such as raising 2 to the power of 10 (represented in math as 210):

var iNum = Math.pow(2, 10);

The first argument of pow() is the base number, in this case, 2. The second argument is the power to raise it to, which is 10 in this example. The last method in this group is sqrt(), which returns the square root of a given number. It takes only one argument, which is the number whose square root you want to find. So to find the square root of 4, you need only this line of code:

var iNum = Math.sqrt(4);
alert(iNum); //outputs "2"

Of course, the square root of 4 is 2, which is output in this code.

You may ask, "What does the square root have to do with exponents?" The square root of a number is actually that number raised to the one-half power; for example, 2 1/2 is the square root of 2.

There is also a complete set of geometric methods included in the Math object. These are displayed in the following table.

Method Description
acos(x) Returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
atan2(y, x) Returns the arc cosine of y/x.
cos(x) Returns the cosine of x.
sin(x) Returns the sine of x.
tan(x) Returns the tangent of x.

It is not recommended to use Math.E as a base for the pow() method. Always use exp() for this because it does special calculations to determine the value more accurately.

Even though these methods are defined by ECMA-262, the results are implementation-dependent because you can calculate each value in many different ways. Consequently, the precision of the results may also vary from one implementation to another.

The last method of the Math object is random(). This method returns a random number between the 0 and 1, not including 0 and 1. This is a favorite tool of Web sites that are trying to display random quotes or random facts upon entry. You can use random() to select numbers within a certain range by using the following formula:

number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)

The floor() method is used here because random() always returns a decimal value, meaning that multiplying it by a number and adding another still yields a decimal value. Most of the time, you want to select a random integer. Because of that, the floor() method is needed. So, if you wanted to select a number between 1 and 10, the code looks like this:

var iNum = Math.floor(Math.random() * 10 + 1);

You see 10 possible values (1 through 10) with the first possible value being 1. If you want to select a number between 2 and 10, then the code looks like this:

var iNum = Math.floor(Math.random() * 9 + 2);

There are only nine numbers when counting from 2 to 10, so the total number of choices is 9 with the first possible value being 2. Many times, it's just easier to use a function that handles the calculation of the total number of choices and the first possible value:

function selectFrom(iFirstValue, iLastValue) {
  var iChoices = iLastValue - iFirstValue + 1;
  return Math.floor(Math.random() * iChoices + iFirstValue);
}
//select from between 2 and 10
var iNum = selectFrom(2, 10);

Using the function, it's easy to select a random item from an Array:

var aColors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
var sColor = aColors[selectFrom(0, aColors.length-1)];

Here, the second parameter to selectFrom() is the length of the array minus 1, which is the last position in an array.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)