Perl Tutorial Perl References

Perl Math - cos() Function



The Perl Math cos() function returns trigonometric cosine of an angle (angle should be in radians). In special cases it returns the following:

  • If the argument is NaN or an infinity, then the result is NaN.

In the graph below, cos(x) vs x is plotted.

Cos Function

Syntax

cos(x)

Parameters

x Specify the angle in radian.

Return Value

Returns the trigonometric cosine of an angle.

Example:

In the example below, cos() function is used to find out the trigonometric cosine of an angle.

use Math::Trig;

print("cos(pi/6) = ".cos(pi/6)."\n");
print("cos(pi/4) = ".cos(pi/4)."\n");
print("cos(pi/3) = ".cos(pi/3)."\n");
print("cos(deg2rad(90)) = ".cos(deg2rad(90))."\n");
print("cos(deg2rad(120)) = ".cos(deg2rad(120))."\n"); 
print("cos(Inf) = ".cos(Inf)."\n");
print("cos(-Inf) = ".cos(-Inf)."\n");
print("cos(NaN) = ".cos(NaN)."\n");

The output of the above code will be:

cos(pi/6) = 0.866025403784439
cos(pi/4) = 0.707106781186548
cos(pi/3) = 0.5
cos(deg2rad(90)) = 6.12323399573677e-17
cos(deg2rad(120)) = -0.5
cos(Inf) = NaN
cos(-Inf) = NaN
cos(NaN) = NaN

This function can also be used to calculate complex cosine of a complex number z. It is a function on complex plane, and has no branch cuts. Mathematically, it can be expressed as:

complex cos

Example:

In the example below, cos() function is used to find out the complex cosine of the given number.

use Math::Complex;

$z1 = 2 + 2*i;
$z2 = 2;
$z3 = 2*i;
print("cos($z1) = ".cos($z1)."\n");
print("cos($z2) = ".cos($z2)."\n");
print("cos($z3) = ".cos($z3)."\n");

The output of the above code will be:

cos(2+2i) = -1.56562583531574-3.29789483631124i
cos(2) = -0.416146836547142
cos(2i) = 3.76219569108363

❮ Perl Math Functions

5