sqrt#
Return the non-negative square root of EXPR.
sqrt computes the principal square root — the unique non-negative
real number whose square equals EXPR. For any EXPR >= 0 the result
is >= 0; sqrt never returns the negative root. If EXPR is
omitted, $_ is used.
The computation is performed in double-precision floating point (IEEE
754 binary64), so the result is a float even when the input is an
integer and even when the mathematical answer is itself an integer.
Synopsis#
sqrt EXPR
sqrt
sqrt(EXPR)
What you get back#
A floating-point number: the non-negative square root of EXPR. For
negative input the result is NaN (and a warning is emitted under
use warnings); see Edge cases. For complex-valued
roots load Math::Complexext, which overloads sqrt so
that sqrt(-1) returns i.
my $r = sqrt 2; # 1.4142135623731
my $r = sqrt; # sqrt of $_
The default argument, precedence, and parsing#
Three parser details shape every sqrt call:
No argument uses
$_.sqrtwith no argument and no parentheses reads the topic variable. Handy insidemapandgrepblocks that already bind$_.Named-unary precedence.
sqrtis a named unary operator, so it binds tighter than most binary operators but looser than multiplication and exponentiation.sqrt 2 + 3meanssqrt(2) + 3, notsqrt(2 + 3)— parenthesise when in doubt.sqrt(...)is a function call. As with every named unary, writing an opening paren immediately after the name turns the remainder into the argument list:sqrt(4) * 2is4(the sqrt of4) times2, i.e.4.
my @roots = map { sqrt } 1, 4, 9; # (1, 2, 3); $_ is the topic
my $x = sqrt 2 + 3; # 4.41421… — sqrt(2) + 3
my $y = sqrt(2 + 3); # 2.23606… — sqrt(5)
Examples#
Classic irrational root. The printed decimal is the closest binary64
approximation, not the exact value:
printf "%.15f\n", sqrt(2); # 1.414213562373095
Pythagorean distance between two points:
sub distance {
my ($x1, $y1, $x2, $y2) = @_;
return sqrt(($x2 - $x1) ** 2 + ($y2 - $y1) ** 2);
}
print distance(0, 0, 3, 4), "\n"; # 5
Zero is its own square root, and so is one:
print sqrt(0), "\n"; # 0
print sqrt(1), "\n"; # 1
Perfect squares round-trip exactly for small integers, because the
mathematical result is representable in binary64:
print sqrt(16), "\n"; # 4
print sqrt(144), "\n"; # 12
print sqrt(1_000_000), "\n"; # 1000
Large perfect squares may not round-trip exactly — the result is the nearest representable float, which can be slightly off:
my $n = 9_007_199_254_740_996; # 2**53 + 4
printf "%.3f\n", sqrt($n) ** 2 - $n; # non-zero in general
Compare to the exponentiation operator, which is the general way to take any real power:
print 2 ** 0.5, "\n"; # same as sqrt(2)
print 27 ** (1/3), "\n"; # cube root of 27 ≈ 3
Using Math::Complexext to get a complex result from a negative input:
use Math::Complex;
my $z = sqrt(-1); # i
print $z, "\n"; # "i"
print sqrt(-4), "\n"; # "2i"
Edge cases#
Negative input without
Math::Complexext: returnsNaNand triggers anInvalid operationwarning underuse warnings.NaNcompares unequal to itself, so never test with==; usePOSIX::isnanor check$x != $x.my $r = sqrt(-1); # NaN print "bad\n" if $r != $r; # NaN self-compare trick
Negative input with
Math::Complexext: onceMath::Complexext is loaded,sqrtis overloaded for complex scalars and returns the principal complex root. Real inputs still go through the built-in.Non-numeric input: coerced to a number using the usual rules — leading whitespace and a numeric prefix are consumed, the rest is ignored. Under
use warningsanisn't numericwarning fires when the string has no numeric prefix at all.undefcoerces to0.print sqrt("9abc"), "\n"; # 3, with a warning under warnings print sqrt(""), "\n"; # 0, with a warning print sqrt(undef), "\n"; # 0, with an uninitialized warning
Floating-point imprecision for perfect squares: for sufficiently large integers, the mathematically exact root may not be representable.
sqrt($n*$n)is not guaranteed to equal$nfor large$n. If you need an exact integer square root, do not usesqrt— useMath::BigIntext’sbsqrtor a dedicated isqrt implementation.Special IEEE values:
sqrt("Inf")isInf;sqrt("NaN")isNaN;sqrt(-0.0)is-0.0(negative zero, which compares equal to0).sqrt("-Inf")isNaN.Integer overflow is not an issue: because the result is always a float,
sqrtnever overflows for any finite numeric input.List context is irrelevant:
sqrtalways returns a single scalar. In list context that scalar is the only element of the returned list.
Differences from upstream#
Fully compatible with upstream Perl 5.42.
See also#
abs— absolute value; pair withsqrtwhen you wantsqrt(abs($x))to sidestep negative input**— exponentiation operator;$x ** 0.5issqrt, and$x ** (1/$n)generalises to other rootshypot— fromPOSIX, computessqrt($x*$x + $y*$y)without intermediate overflowMath::Complexext — overloadssqrtand friends so thatsqrt(-1)returnsiinstead ofNaNMath::BigIntext,Math::BigFloatext — arbitrary-precision square roots viabsqrtwhenbinary64is not enough