13.3.2 Trigonometric Functions
13.3.2 Trigonometric Functions
Although standard Perl provides a few trigonometric functions, the set is limited. Math::Cephes allows us to compute the values of all trigonometric functions and their inverses, using angle measurement in radian or degrees. The following program illustrates some of the functions.
Program 13.3
#!/usr/bin/perl #file trig.pl use Math::Cephes qw(:trigs :constants); my $angleR = $Math::Cephes::PIO4; my $angleD = 45; my $value = 1; print "cosine (PIO4 rad) = " . Math::Cephes::cos ($angleR) . "\n"; print "sine (PIO4 rad) = " . Math::Cephes::sin ($angleR) . "\n"; print "tangent (PIO4 rad) = " . Math::Cephes::tan ($angleR) . "\n"; print "cotangent (PIO4 rad) = " . Math::Cephes::cot ($angleR) . "\n"; print "cosine (45 deg) = " . Math::Cephes::cosdg ($angleD) . "\n"; print "sine (45 deg) = " . Math::Cephes::sindg ($angleD) . "\n"; print "tangent (45 deg) = " . Math::Cephes::tandg ($angleD) . "\n"; print "cotangent (45 deg) = " . Math::Cephes::cotdg ($angleD) . "\n"; print "acos ($value) = " . Math::Cephes::acos ($value) . " rad \n"; print "asin ($value) = " . Math::Cephes::asin ($value) . " rad \n"; print "atan ($value) = " . Math::Cephes::atan ($value) . " rad \n";
Once again, the program is simple and performs only an illustrative purpose. It imports the set of trigonometric functions as a group using the keyword :trigs. It also imports the constants using the :constants keyword discussed earlier. $angleR has the value radians, and $angleD is 45 degrees. Both represent the same angle. Each of the sin, cos, tan and cot functions takes an angle in radians, whereas sindg, cosdg, tandg and cotdg each takes an angle argument given in degrees. Each of the inverse trigonometric functions: asin, acos and atan returns its result in radians only. The output of the program is given below.
osine (PIO4 rad) = 0.707106781186548
sine (PIO4 rad) = 0.707106781186547
tangent (PIO4 rad) = 1
cotangent (PIO4 rad) = 1
cosine (45 deg) = 0.707106781186548
sine (45 deg) = 0.707106781186548
tangent (45 deg) = 1
cotangent (45 deg) = 1
acos (1) = 0 rad
asin (1) = 1.5707963267949 rad
atan (1) = 0.785398163397448 rad
Math::Cephes can obtain values of all trigonometric functions for complex arguments as well.
