Recipe 2.11 Calculating More Trigonometric Functions

2.11.1 Problem

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

2.11.2 Solution

Perl provides only sin, cos, and atan2 as standard functions. From these, you can derive tan and all other trig functions (if you're intimately familiar with esoteric trig identities):

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

2.11.3 Discussion

The tan function will cause a division-by-zero exception when \$theta is p/2, 3p/2, and so on, because the cosine is 0 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;```

The sin, cos, and atan2 functions in perlfunc(1) and Chapter 29 of Programming Perl; the documentation for the standard Math::Trig module; we talk about trigonometry in the context of imaginary numbers in Recipe 2.14; we talk about the use of eval to catch exceptions in Recipe 10.12  Chapter 1. Strings  Chapter 2. Numbers  Introduction  Recipe 2.1 Checking Whether a String Is a Valid Number  Recipe 2.2 Rounding Floating-Point Numbers  Recipe 2.3 Comparing Floating-Point Numbers  Recipe 2.4 Operating on a Series of Integers  Recipe 2.5 Working with Roman Numerals  Recipe 2.6 Generating Random Numbers  Recipe 2.7 Generating Repeatable Random Number Sequences  Recipe 2.8 Making Numbers Even More Random  Recipe 2.9 Generating Biased Random Numbers  Recipe 2.10 Doing Trigonometry in Degrees, Not Radians  Recipe 2.11 Calculating More Trigonometric Functions  Recipe 2.12 Taking Logarithms  Recipe 2.13 Multiplying Matrices  Recipe 2.14 Using Complex Numbers  Recipe 2.15 Converting Binary, Octal, and Hexadecimal Numbers  Recipe 2.16 Putting Commas in Numbers  Recipe 2.17 Printing Correct Plurals  Recipe 2.18 Program: Calculating Prime Factors  Chapter 3. Dates and Times  Chapter 4. Arrays  Chapter 5. Hashes  Chapter 6. Pattern Matching  Chapter 7. File Access  Chapter 8. File Contents  Chapter 9. Directories  Chapter 10. Subroutines  Chapter 11. References and Records  Chapter 12. Packages, Libraries, and Modules  Chapter 13. Classes, Objects, and Ties  Chapter 14. Database Access  Chapter 15. Interactivity  Chapter 16. Process Management and Communication  Chapter 17. Sockets  Chapter 18. Internet Services  Chapter 19. CGI Programming  Chapter 20. Web Automation  Chapter 21. mod_perl  Chapter 22. XML