Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

Calculating More Trigonometric Functions

Problem

You want to calculate values for trigonometric functions like sine, tangent, or arc-cosine.

Solution

Perl provides only sin, cos, and atan2 as standard functions. From these, you can derive tan and the other trig functions:

sub tan {
    my $theta = shift;

    return sin($theta)/cos($theta);
}

The POSIX module provides a wider range of trig functions:

use POSIX;

$y = acos(3.7);

The Math::Trig module provides a complete set of functions and supports operations on or resulting in complex numbers:

use Math::Trig;

$y = acos(3.7);

Discussion

The tan function will cause a division-by-zero exception when $theta is

Discussion

,

Discussion

, and so on, because the cosine is for these values. Similarly, tan and many other functions from Math::Trig may generate the same error. To trap these, use eval:

eval {
    $y = tan($pi/2);
} or return undef;

See Also

The sin, cos, and atan2 functions in perlfunc (1) and Chapter 3 of Programming Perl; we talk about trigonometry in the context of imaginary numbers in Section 2.15; we talk about the use of eval to catch exceptions in Section 10.12

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata