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")returns1because the string is numified to0first. Underuse warningsthis produces anArgument "hello" isn't numeric in coswarning. Validate input withlooks_like_numberfromScalar::Utilif the source is untrusted.Very large arguments lose precision.
cosfirst reduces its argument modulo2π, and for|x|on the order of1e16the nearest representable double differs fromxby 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.undefcoerces to0and returns1, with the usualuninitializedwarning underuse warnings.IEEE specials:
cos("inf"),cos("-inf"), andcos("nan")all returnNaN. Compare with$result != $result(the only value not equal to itself) to detectNaN, or usePOSIX::isnan.No complex-number support in the built-in. For complex arguments use
Math::Complexext, which overloadscosvia 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 alongsidecosatan2— two-argument arctangent, the usual building block for inverse trig (acos,asin) in pure Perlsqrt— square root; appears in the classicalacosidentityacos(x) = atan2(sqrt(1 - x*x), x)Math::Trigext —acos,asin,atan, hyperbolic variants,deg2rad/rad2deg, and great-circle helpersMath::Complexext — overloadscos(and the rest of the trig family) for complex argumentsPOSIX— exposesacosdirectly, plusisnan/isinffor detecting the non-finite results discussed above