JavaScript EditorFreeware JavaScript Editor     Perl Tutorials 

Main Page Previous Section Next Section

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));

sub deg2rad {
    my $degrees = shift;
    return ($degrees / 180) * PI;

sub rad2deg {
    my $radians = shift;
    return ($radians / PI) * 180;

Alternatively, use the standard Math::Trig module:

use Math::Trig;

$radians = deg2rad($degrees);
$degrees = rad2deg($radians);

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 $radians = deg2rad($degrees);
    my $result = sin($radians);

    return $result;

2.10.4 See Also

The sin, cos, and atan2 functions in perlfunc(1) and Chapter 29 of Programming Perl; the documentation for the standard POSIX and Math::Trig modules (also in Chapter 32 of Programming Perl)

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Verifier     Perl Tutorials