--- name: sqrt signature: 'sqrt EXPR' since: 5.0 status: documented categories: ["Numeric functions"] --- ```{index} single: sqrt; Perl built-in ``` *[Numeric functions](../perlfunc-by-category)* # 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, [`$_`](../perlvar) 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 ```perl 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](#edge-cases). For complex-valued roots load {ext}`Math::Complex`, which overloads `sqrt` so that `sqrt(-1)` returns `i`. ```perl 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 [`$_`](../perlvar)**. `sqrt` with no argument and no parentheses reads the topic variable. Handy inside [`map`](map) and [`grep`](grep) blocks that already bind [`$_`](../perlvar). - **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`. ```perl 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: ```perl printf "%.15f\n", sqrt(2); # 1.414213562373095 ``` Pythagorean distance between two points: ```perl 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: ```perl 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`: ```perl 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: ```perl 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: ```perl print 2 ** 0.5, "\n"; # same as sqrt(2) print 27 ** (1/3), "\n"; # cube root of 27 ≈ 3 ``` Using {ext}`Math::Complex` to get a complex result from a negative input: ```perl use Math::Complex; my $z = sqrt(-1); # i print $z, "\n"; # "i" print sqrt(-4), "\n"; # "2i" ``` ## Edge cases - **Negative input without {ext}`Math::Complex`**: 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`. ```perl my $r = sqrt(-1); # NaN print "bad\n" if $r != $r; # NaN self-compare trick ``` - **Negative input with {ext}`Math::Complex`**: once {ext}`Math::Complex` 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`](undef) coerces to `0`. ```perl 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 {ext}`Math::BigInt`'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`](abs) — absolute value; pair with `sqrt` when you want `sqrt(abs($x))` to sidestep negative input - [`**`](../perlop) — exponentiation operator; `$x ** 0.5` is `sqrt`, and `$x ** (1/$n)` generalises to other roots - `hypot` — from [`POSIX`](../../POSIX), computes `sqrt($x*$x + $y*$y)` without intermediate overflow - {ext}`Math::Complex` — overloads `sqrt` and friends so that `sqrt(-1)` returns `i` instead of `NaN` - {ext}`Math::BigInt`, {ext}`Math::BigFloat` — arbitrary-precision square roots via `bsqrt` when `binary64` is not enough