Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Selecting Random Numbers

Nested Splitting

Split Ends

How long is a piece of string?

Random Numbers & Random Events

Scrolling Text

Math functions in JavaScript

You are here: irt.org | Articles | JavaScript | Text, String, and Number | Math functions in JavaScript [ previous next ]

Published on: Saturday 21st March 1998 By: Janus Boye

Introduction

Math is power. So says one of the many ads on the Internet. JavaScript has the power, to do all functions that are on a normal pocket calculator, and even a few more.

Try out the pocket calculator example.

Did you by the way, remember to turn the calculator on?

This article will focus on the Math object. Towards the end, I've put a complete listing, of all the properties and methods, you may use, and as an example of those, I've provided some simple programs. The first will give you a random number, and the second, will show you how to round a number, to the nearest integer.

The top level Predefined JavaScript Object Math

Math is a built-in object that has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi.

When using Math, it is important to remember that all properties and methods of Math are static. You refer to the property PI as Math.PI and you call the method as Math.sin(x), where x is the method's argument. Properties are defined with the full precision of real numbers in JavaScript. More on precision later.

You will often find it convenient to use the with statement, when a section of code uses several Math properties and methods, so you don't have to type 'Math' repeatedly. For example:

with (Math) {
     a = PI * r*r
     y = r*sin(theta)
     x = r*cos(theta)
     b = a + y/x
}

The limitations

Before moving onto working examples and much more, we need to address the limitations of using Math in JavaScript.

One of the interesting features of JavaScript is, that the precision it uses to judge the accuracy of its calculation algorithms is noticeably lower than that of other programming languages. Despite it now being at revision 1.2, this standard has not yet been improved.

To give you an idea of the nature and depth of the problem, although for instance Authorware, Turbo Pascal, Excel and even Word6 will calculate the following correctly, multiplying:

0.119 by 100 in JavaScript evaluates to 11.899999.

0.14 by 100 in JavaScript evaluates to 14.0000000000002

Normally in JavaScript a value has 16 digits of precision, and this just seems to be the limitations inherent in the routines used.

When to use Math in JavaScript, and why?

As you move along with JavaScript, you are going to find that using Math in JavaScript may be a good place to start. It's nice and simple, but still gives you some pretty big challenges, if that's what you want.

With Math, you may start with those sweet functions, that give you a random number (pseudo-random that is). You could use this to do a random function, display a random image and much more.

Random numbers

Enough said about limitations, precision, and the cross-browser issue, let's move on to a example, that'll show you how to get a pseudo-random number between 0 and 1. The random number generator is seeded from the current time, as in Java.

//Returns a random number between 0 and 1
function getRandom() {
     return Math.random();
}

In this examples and others we have create out own getRandom() function to make it easier to use the required method. That way we don't have to keep including 'Math'.

To use the above getRandom() function is simplicity itself:

alert(getRandom());
var a = getRandom();

You can read more on random numbers and their limitations in Selecting Random Number by Martin Webb.

Rounding numbers

In other cases, you might want a number to be rounded to the nearest integer, this little example will show you how:

document.write ('<P>The rounded value is ' + Math.round(20.49));  //Displays the value of 20
document.write ('<P>The rounded value is ' + Math.round(20.5));   //Displays the value of 21
document.write ('<P>The rounded value is ' + Math.round(-20.5)):  //Displays the value of -20
document.write ('<P>The rounded value is ' + Math.round(-20.51)): //Displays the value of -21

If the fractional portion of number is .5 or greater, the argument is rounded to the next highest integer. If the fractional portion of number is less than .5, the argument is rounded to the next lowest integer.

Because round() is a static method of Math, you always use it as Math.round(), rather than as a method of a Math object you created. In other words the following is wrong:

var a = 13;
a.round();

And would cause a JavaScript error.

Special numeric values

There are several special numeric values used by JavaScript. When a floating-point value becomes larger than the largest representable type, the result is a special infinity value, which JavaScript prints as Infinity. Similarly, when a negative value becomes more negative than the most negative representable number, the result is negative infinity, printed as -Infinity. (Internet Explorer 3.0 prints these special infinity values in a less intuitive fashion; this is fixed in IE4.0).

Another special JavaScript numeric value is returned when a mathematical operation (such as division by zero) yields an undefined result or an error. In this case, the result is the special Not-a-Number value, printed as NaN. The special Not-a-Number value has special behaviour: it does not compare equal to any number, including itself! For this reason, a special function isNaN() is required to test for this value. In Navigator 2.0, the NaN value and isNaN() do not work correctly on Windows and other platforms. On 2.0 Windows platforms, 0 is returned instead of NaN when a numeric value is undefined. Similarly, NaN does not work in Internet Explorer 3.0, although it will in future versions. In IE 3.0, isNaN() always returns false, and 0 is returned instead of NaN.

In Navigator 3.0 (but not IE 3.0), there are constants defined for each of these special numeric values. These constants are listed below:

ConstantMeaning
Number.MAX_VALUELargest representable number
Number.MIN_VALUEMost negative representable number
Number.NaNSpecial not-a-number value
Number.POSITIVE_INFINITYSpecial value to represent infinity
Number.NEGATIVE_INFINITYSpecial value to represent negative infinity

Don't know much about trigonometry

Trigonometry hasn't gotten much simpler since you last worked with it, but JavaScript gives you a few methods, that'll basically does most of the work for you.

Let's say you want the sine of a number.

//Returns the sine of a number
function getSine(x) {
   return Math.sin(x);
}

The sin() method returns a numeric value between –1 and 1, which represents the sine of the argument. Because sin() is a static method of Math, you always use it as Math.sin(), rather than as a method of a Math object you created.

If you want to find the cosine of tangent of x, you simply just replace Math.sin() with either Math.cos() or Math.tan().

Reverse trigonometric

In real world math, and in JavaScript Math, there is a reverse trigonometric function acos. The acos() method returns the arccosine (in radians of a number). If you for some odd reason want to use this on your page, you could do the following:

function getAcos(x) {
  return Math.acos(x);
}

The acos() method returns a numeric value between 0 and pi radians. If the value of number is outside the range, it returns 0.

If you pass –1 to getAcos(), it returns 3.14159265389793; if you pass 2, it returns 0 because 2 is out of range.

If you want to find the arcsine of arctangent (in radians), you simply just replace acos() with either asin() or atan().

Property Summary

Here's a listing of all the properties in Math:

Use these properties, as in the example below:

//Get's the value of PI
function getPi() {
   return Math.PI;
}

You may replace PI with any other Math property, and it'll work accordingly.

Method Summary

Use these methods, as in the random or rounding numbers example, or in the below, that'll return the squareroot of x.

//Returns the squareroot of a given number
function getRoot(x) {
  return Math.sqrt(x);
}

Conclusion

Well, that's it. Now the sky's the limit. I hope this little article have helped you en-route to understanding the powerful Math methods and properties in JavaScript.

On the net, you'll find several JavaScripts, that'll do some really advanced mathematics in JavaScript.

Come back later to this site, to further understand the calculator that I showed you in the beginning, plus I'll show you a trick, that'll work as a nice workaround to the problem, with JavaScript being inaccurate.

Related items

Selecting Random Numbers

Nested Splitting

Split Ends

How long is a piece of string?

Random Numbers & Random Events

Scrolling Text

©2018 Martin Webb