Numeric functions

cos#

Return the cosine of a number given in radians.

cos is the standard trigonometric cosine: it takes an angle measured in radians and returns the ratio of the adjacent side to the hypotenuse of the corresponding right triangle. If EXPR is omitted, cos operates on $_. The result is always a floating-point number in the closed interval [-1, 1].

Synopsis#

cos EXPR
cos

What you get back#

A double-precision float in [-1, 1]. Perl forwards the call to the platform’s C cos(3) routine, so the precision and rounding behaviour match your libm. Special values follow IEEE 754: cos(0) is exactly 1, cos("inf") and cos("nan") are both NaN.

Radians, not degrees#

The single most common mistake with cos is feeding it degrees. A full turn is 2 * π radians, not 360. Convert once and keep the converted value:

use POSIX qw(acos);
my $pi = acos(-1);                  # π to full double precision

sub deg2rad { $_[0] * $pi / 180 }

print cos( deg2rad(60) ), "\n";     # 0.5
print cos( 60 ), "\n";              # -0.952412980415 — wrong if you meant degrees

Math::Trigext exports deg2rad and rad2deg if you would rather not write the conversion yourself.

Examples#

Walk the unit circle in eight steps and print (cos θ, sin θ):

use POSIX qw(acos);
my $pi = acos(-1);

for my $k (0 .. 7) {
    my $theta = $k * $pi / 4;
    printf "%.3f  %+.3f  %+.3f\n",
           $theta, cos($theta), sin($theta);
}

Compare cos against its Taylor series around zero. For small $x the four-term expansion is already accurate to ten decimal places — a useful sanity check when porting numeric code:

sub cos_taylor {
    my $x = shift;
    my $x2 = $x * $x;
    1 - $x2/2 + $x2*$x2/24 - $x2*$x2*$x2/720;
}

my $x = 0.3;
printf "libm:   %.15f\n", cos($x);
printf "taylor: %.15f\n", cos_taylor($x);

Default argument. Inside a while (<>) loop cos without an argument reads the current line — almost always a bug, but the language allows it:

$_ = 0;
print cos, "\n";                    # 1

Inverse cosine via the identity from perlfunc:

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

print acos(0.5), "\n";              # 1.0471975511966 (= π/3)

Using Math::Trigext for the full set of inverse and hyperbolic functions rather than rolling your own:

use Math::Trig;
print acos(0.5), "\n";              # same result, no hand-written formula

Edge cases#

  • Non-numeric arguments coerce to 0. cos("hello") returns 1 because the string is numified to 0 first. Under use warnings this produces an Argument "hello" isn't numeric in cos warning. Validate input with looks_like_number from Scalar::Util if the source is untrusted.

  • Very large arguments lose precision. cos first reduces its argument modulo , and for |x| on the order of 1e16 the nearest representable double differs from x by more than π. The result is still a number in [-1, 1], but it is essentially random. Reduce the angle yourself before the call if you are accumulating a phase over many iterations.

  • undef coerces to 0 and returns 1, with the usual uninitialized warning under use warnings.

  • IEEE specials: cos("inf"), cos("-inf"), and cos("nan") all return NaN. Compare with $result != $result (the only value not equal to itself) to detect NaN, or use POSIX::isnan.

  • No complex-number support in the built-in. For complex arguments use Math::Complexext, which overloads cos via operator overloading:

    use Math::Complex;
    my $z = cplx(1, 2);
    print cos($z), "\n";              # 2.03272300701967-3.0518977991518i
    

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • sin — sine of an angle in radians; the companion function most often used alongside cos

  • atan2 — two-argument arctangent, the usual building block for inverse trig (acos, asin) in pure Perl

  • sqrt — square root; appears in the classical acos identity acos(x) = atan2(sqrt(1 - x*x), x)

  • Math::Trigextacos, asin, atan, hyperbolic variants, deg2rad/rad2deg, and great-circle helpers

  • Math::Complexext — overloads cos (and the rest of the trig family) for complex arguments

  • POSIX — exposes acos directly, plus isnan/isinf for detecting the non-finite results discussed above