Perl CookbookPerl CookbookSearch this book

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 (2π 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 π 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 π 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)



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.