It is common (but incorrect) for pseudorandom number genera‐
tors (PRNGs) to simply be called “random number generators.”
PRNGs produce numbers that for most practical applications
appear to be random, but true random number generation is a very
difficult problem.
Trigonometric Functions
There are no surprises here. Sine, cosine, tangent, and their inverses are all available,
as shown in
. All trigonometric functions in the
Math
library operate on
radians, not degrees.
Table 16-5. Number trigonometric functions
Function
Description
Examples
Math.sin(x)
Sine of x radians
Math
.
sin
(
Math
.
PI
/
2
)
// 1
Math
.
sin
(
Math
.
PI
/
4
)
// ~0.707
Math.cos(x)
Cosine of x radians
Math
.
cos
(
Math
.
PI
)
// -1
Math
.
cos
(
Math
.
PI
/
4
)
// ~0.707
Math.tan(x)
Tangent of x radians
Math
.
tan
(
Math
.
PI
/
4
)
// ~1
Math
.
tan
(
0
)
// 0
Math.asin(x)
Inverse sine (arcsin) of x
(result in radians)
Math
.
asin
(
0
)
// 0
Math
.
asin
(
Math
.
SQRT1_2
)
// ~0.785
Math.acos(x)
Inverse cosine (arccos) of x
(result in radians)
Math
.
acos
(
0
)
// ~1.57+
Math
.
acos
(
Math
.
SQRT1_2
)
// ~0.785+
Math.atan(x)
Inverse tangent (arctan) of x
(result in radians)
Math
.
atan
(
0
)
// 0
Math
.
atan
(
Math
.
SQRT1_2
)
// ~0.615
Math.atan2(y, x0)
Counterclockwise angle (in
radians) from the x-axis to the
point (x, y)
Math
.
atan2
(
0
,
1
)
// 0
Math
.
atan2
(
1
,
1
)
// ~0.785
If you’re dealing with degrees, you’ll need to convert them to radians. The calculation
is easy: divide by 180 and multiply by π. It’s easy to write helper functions:
function
deg2rad
(
d
) {
return
d
/
180
*
Math
.
PI
; }
function
rad2deg
(
r
) {
return
r
/
Math
.
PI
*
180
; }
Trigonometric Functions | 235