Numeric functions

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 $_. sqrt with no argument and no parentheses reads the topic variable. Handy inside map and grep blocks that already bind $_.

  • Named-unary precedence. sqrt is a named unary operator, so it binds tighter than most binary operators but looser than multiplication and exponentiation. sqrt 2 + 3 means sqrt(2) + 3, not sqrt(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) * 2 is 4 (the sqrt of 4) times 2, 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: returns NaN and triggers an Invalid operation warning under use warnings. NaN compares unequal to itself, so never test with ==; use POSIX::isnan or check $x != $x.

    my $r = sqrt(-1);                 # NaN
    print "bad\n" if $r != $r;        # NaN self-compare trick
    
  • Negative input with Math::Complexext: once Math::Complexext is loaded, sqrt is 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 warnings an isn't numeric warning fires when the string has no numeric prefix at all. undef coerces to 0.

    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 $n for large $n. If you need an exact integer square root, do not use sqrt — use Math::BigIntext’s bsqrt or a dedicated isqrt implementation.

  • Special IEEE values: sqrt("Inf") is Inf; sqrt("NaN") is NaN; sqrt(-0.0) is -0.0 (negative zero, which compares equal to 0). sqrt("-Inf") is NaN.

  • Integer overflow is not an issue: because the result is always a float, sqrt never overflows for any finite numeric input.

  • List context is irrelevant: sqrt always 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 with sqrt when you want sqrt(abs($x)) to sidestep negative input

  • ** — exponentiation operator; $x ** 0.5 is sqrt, and $x ** (1/$n) generalises to other roots

  • hypot — from POSIX, computes sqrt($x*$x + $y*$y) without intermediate overflow

  • Math::Complexext — overloads sqrt and friends so that sqrt(-1) returns i instead of NaN

  • Math::BigIntext, Math::BigFloatext — arbitrary-precision square roots via bsqrt when binary64 is not enough