The Math object

The JavaScript developer has access to a bunch of commonplace mathematical constants and functions through the Math object. As official reference you should check the ECMA-262 5.1 standard, even if I should confess that I find more readable the Mozilla Developer page.

To calculate a circumference, it is nice to have a PI constant available:
var radius = 1;
var circ = 2 * Math.PI * radius;
console.log("Circumference is ", circ);
The resulting value should be something around 6.283185307179586.

We can convert a number to integer by approximation using round(), or we can use ceil() and floor(), to flatten the result to the left or to the right.
Let's see what happen applying these functions to the natural logarithm of 10:
var value = Math.LN10;
console.log(Math.floor(value), " <= ", value, " <= ", Math.ceil(value));
console.log("Rounding", value, " -> ", Math.round(value));
The max() and min() functions accept in input any (reasonable) number of parameters, and its returned value is the bigger or smaller one in the lot.
var values = [ -42, 5, Math.E ];
console.log(Math.max(values[0], values[1], values[2]));
console.log(Math.min(values[0], values[1], values[2]));
Min is -42, max is 5.

There are also the usual functions to calculate exponential values, Math.exp(), logarithm,

Math.log(), power, Math.pow(), a short cut for square roots, sqrt(), and the common trigonometric functions.

Playing around with JavaScript numerical functions, you can end up getting Infinity, -Infinity, and NaN.
console.log("Divide by zero:", 3 / 0); // Infinity
console.log("Divide by zero:", -3 / 0);  // -Infinity
console.log("Not a number:", 0 / 0);
console.log("Not a number:", Math.sqrt(-2)); // Nan

No comments:

Post a Comment