11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Table 7-4: Methods Provided by the Math Object<br />

Method Returns<br />

Math.tan(arg) Tangent of arg<br />

<strong>The</strong>re are several aspects of the Math object that need to be kept in mind. <strong>The</strong> trigonometric<br />

methods work in radians, so you need to multiply any degree measurements by / 180 before<br />

using them. Also, because of the imprecise characteristic of floating-point operations, you might<br />

notice minor deviations from the results you expect. For example, though the sine of is 0, the<br />

following code:<br />

alert(Math.sin(Math.PI));<br />

gives the result<br />

This value is very close to zero, but just large enough to trip up sensitive calculations.<br />

It might seem that Math does not provide the capability to compute logarithms in bases other<br />

than e. Indeed it does not, directly. However, the following mathematical identity<br />

loga n = (loge n) / (loge a)<br />

can be used to compute logarithms in an arbitrary base. For example, you can compute the log<br />

base 2 of 64 as<br />

var x = Math.log(64) / Math.log(2);<br />

Random Numbers<br />

Because the Math.random() method returns values between zero and one, you must<br />

normalize its return value to fit the range of numbers required of your application. An easy way<br />

to get random integers in the range m to n (inclusive) is as follows:<br />

Math.round(Math.random() * (n - m)) + m;<br />

So to simulate a die roll you would use<br />

roll = Math.round(Math.random() * (6 - 1)) + 1;<br />

Generating random numbers in this manner is sufficient for most applications, but if ―high<br />

quality‖ randomness is required, a more advanced technique should be used.<br />

Easing Math Computations<br />

When working extensively with the Math object, it is often convenient to use the with<br />

statement. Doing so allows you to use Math properties without prefixing them with ―Math.‖ <strong>The</strong><br />

concept is illustrated by the following example (computing the length of a side of a triangle with<br />

the Law of Cosines):<br />

with (Math)<br />

{

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!