Java Script Trigonometric Methods
By Stephen Bucaro
The Java Script Math object provides the trigonometric functions cosine, sine,
tangent, along with many others. All the trigonometric functions return an angular value
in radians. Why use radians rather than degrees?
The 360 degree rotation angle of a circle is totally fabricated by man and is cumbersome
to use in mathematical calculations. Radians are in tune with nature as 2 pi radians rotates
an arc in a complete circle. Radians make it possible to use algebra to manipulate geometric
shapes in Cartesian space (named after the French man Rene Descartes who came up with it while
dabbling in, among other things, mathematics). To put it another way, we probably wouldn't
have 3D games or computer generated movies without radians.
If you still need to work with degrees, the functions shown below can be used to convert
radians to degrees and degrees to radians.
function rad2deg(radians)
{
degrees = 360 * radians/(2 * Math.PI);
return degrees;
}
function deg2rad(degrees)
{
radians = (2 * Math.PI * degrees)/360;
return radians;
}
As an example, lets use the Math.tan function to solve a common trigonometry problem.
We want to determine the height of a structure. We setup a surveyors telescope 100 meters from
the base of the structure and rotate the telescope 33.8 degrees to point at the peak of the
structure. We can use the basic trigonometric equation shown below.
tan = opposite/adjacent
For our problem we need to rearrange the equation to that shown below.
height = tan 33.8 degrees * 100;
Shown below is the code required to solve the problem.
var radians = (2 * Math.PI * 33.8)/360;
var tan = Math.tan(radians);
var height = tan * 100;
document.write(height);
The first line of code converts degrees to radians for use with the Math.tan function.
The second line returns the tangent of the angle. Since the tangent is the ratio of the height
of the object to the distance between the surveyors telescope and the structure, multiplying this
distance by the tangent of the angle will provide us with the height of the object. The last
line of code displays the height of the structure (66.9 meters).
The JavaScript Math object gives you powerful routines that let you generate random
numbers, convert numbers to strings and strings to numbers, and perform trigonometric functions
and much more. After this introduction, you should be able to create some interesting JavaScript applications.
More Java Script Code: • The break Statement • Format a Number as Currency • Window Object Properties and Methods • Use Escape to Replace Dangerous Characters • Comparison Operators • Compare Two Strings • Rounding a Number with JavaScript • JavaScript .big and .small to Change Text Size • Window onload Event • JavaScript Operators
