﻿ Perl Tutorial Freeware JavaScript Editor     Perl Tutorials ﻿

### Recipe 2.10 Doing Trigonometry in Degrees, Not Radians

#### 2.10.1 Problem

You want your trigonometry routines to operate in degrees instead of Perl's native radians.

#### 2.10.2 Solution

Convert between radians and degrees (2p radians equals 360 degrees):

```use constant PI => (4 * atan2 (1, 1));

my \$degrees = shift;
return (\$degrees / 180) * PI;
}

my \$radians = shift;
return (\$radians / PI) * 180;
}```

Alternatively, use the standard Math::Trig module:

```use Math::Trig;

#### 2.10.3 Discussion

If you're doing a lot of trigonometry, look into using either the standard Math::Trig or POSIX modules. They provide many more trigonometric functions than are defined in the Perl core. Otherwise, the first solution will define the rad2deg and deg2rad functions. The value of p isn't built directly into Perl, but you can calculate it to as much precision as your floating-point hardware provides. In the Solution, the PI function is a constant created with use constant. Instead of having to remember that p is 3.14159265358979 or so, we use the built-in function call, resolved at compile time, which, besides sparing us from memorizing a long string of digits, is also guaranteed to provide as much accuracy as the platform supports.

If you're looking for the sine in degrees, use this:

```# deg2rad and rad2deg defined either as above or from Math::Trig
sub degree_sine {
my \$degrees = shift;
my \$result = sin(\$radians);

return \$result;
}``` JavaScript Verifier     Perl Tutorials