Function cos() in Perl

In the Perl programming language has a built-in function cos(). This function returns the value of trigonometric functions the cosine of your argument.

Here's an example:

▶ Run
#!/usr/bin/perl

print cos( 3.14159265358979 );

This program will display the number -1. The cosine π is -1, this is what is displayed by the program.

Arguments

my $value = cos($rad);

Argument Perl functions cos() is a number in radians.

If the functions cos() to pass a single argument, the function will operate on it.

If you do not pass any argument, the function will work with variable $_. Here is an example (the program displays the number 1):

▶ Run
#!/usr/bin/perl

$_ = 2 * 3.14159265358979;

print cos;

If the functions cos() pass more than one argument, it will error:

Too many arguments for cos at script.pl line 3, near "0)"
Execution of script.pl aborted due to compilation errors.

Return value

Function cos() always returns a number. The range of possible values is -1, to 1.

Example of returned value: 0.995004165278026 (this value is when you use the argument 0.1).

Work with degrees

The argument cos() is a number in radians. If you need to calculate the cosine degrees, that they need to be converted to radians. To convert degrees to radians use the formula rad = degree * π/180.

Here is a sample program that prints a table with degrees, radians and the cosine ratio:

▶ Run
#!/usr/bin/perl

use utf8;
use strict;
use warnings;
use feature qw(say);

use Math::Trig;

say 'deg      rad  cos(rad)';

for (my $degree = 0; $degree<=360; $degree += 15) {
    my $rad = $degree * pi() / 180;
    say sprintf '%3d  %0.5f  % 0.5f', $degree, $rad, cos($rad);
}

The program uses a Perl module Math::Trig. When the connection becomes available function pi(), which returns the number π.

Here is the output of this program:

deg      rad  cos(rad)
  0  0.00000   1.00000
 15  0.26180   0.96593
 30  0.52360   0.86603
 45  0.78540   0.70711
 60  1.04720   0.50000
 75  1.30900   0.25882
 90  1.57080   0.00000
105  1.83260  -0.25882
120  2.09440  -0.50000
135  2.35619  -0.70711
150  2.61799  -0.86603
165  2.87979  -0.96593
180  3.14159  -1.00000
195  3.40339  -0.96593
210  3.66519  -0.86603
225  3.92699  -0.70711
240  4.18879  -0.50000
255  4.45059  -0.25882
270  4.71239  -0.00000
285  4.97419   0.25882
300  5.23599   0.50000
315  5.49779   0.70711
330  5.75959   0.86603
345  6.02139   0.96593
360  6.28319   1.00000

Related topics

Official documentation

Here is the output of the command perldoc -f cos:

       cos EXPR
       cos     Returns the cosine of EXPR (expressed in radians).  If EXPR is
               omitted, takes the cosine of $_.

               For the inverse cosine operation, you may use the
               "Math::Trig::acos()" function, or use this relation:

                   sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }

Other articles

Comments