sqrt

Returns the square root of a number, or NAN when the input is negative.

Signature
sqrt(float $num): float
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$numfloatThe argument to process. Negative values produce NAN.

Return value

floatThe square root of num, or the special value NAN for negative numbers.

Errors

Throws a TypeError if num is not a number and cannot be converted to a float. Negative input returns NAN rather than throwing.

sqrt() always returns a float, even for perfect squares: sqrt(9) is float(3), not int(3). It is equivalent to pow($n, 0.5) and $n ** 0.5, but sqrt() is faster and clearer.

Negative input gives NAN, not an error

This is the one that bites. sqrt(-4) does not throw and does not warn — it returns NAN, which then propagates silently through every subsequent calculation, so the failure surfaces far from its cause. If your input can be negative, check first, or test the result with is_nan(). A plain $result == NAN comparison is always false and will not help you.

Perfect squares and precision

sqrt() is correctly rounded, so sqrt(9) == 3.0 is reliably true for exact squares. But chained arithmetic is not: sqrt(2) * sqrt(2) is 2.0000000000000004, not 2. Compare with an epsilon rather than ==.

Use hypot() for distances

For sqrt($a * $a + $b * $b), reach for hypot($a, $b) instead. It computes the same value but avoids intermediate overflow and underflow when the legs are very large or very small.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Calculate the distance between two points from their squared differences
  • Derive a standard deviation from a computed variance
  • Find the side length of a square given its area
  • Compute a vector magnitude for normalising direction

Frequently asked questions

What does sqrt() return for a negative number?

It returns the float NAN, without any warning or exception. Check the input before calling, or test the result with is_nan(), because comparing against NAN with == always evaluates to false.

Does sqrt() return an int for perfect squares?

No, sqrt() always returns a float, so sqrt(9) is float(3). Cast with (int) if you need an integer, and use fmod($n, 1) == 0 or a comparison against round() to test whether a number is a perfect square.

What is the difference between sqrt() and pow($n, 0.5)?

They return the same value, but sqrt() is faster and more readable. Both give NAN for negative input; neither works for cube roots, where you need pow($n, 1/3) with a sign correction for negative bases.

More examples

Standard deviation of a data set

Variance is the mean of the squared differences from the mean; the standard deviation is its square root. sqrt() is the last step, converting a squared quantity back into the original units.

Example · php
<?php
$samples = [42, 61, 55, 78, 39, 64];
$mean = array_sum($samples) / count($samples);

$variance = array_sum(array_map(
    fn($v) => ($v - $mean) ** 2,
    $samples
)) / count($samples);

echo 'mean:   ', round($mean, 4), "\n";
echo 'var:    ', round($variance, 4), "\n";
echo 'stddev: ', round(sqrt($variance), 4), "\n";

Handling negative input safely

Wrapping sqrt() so it returns null for negative input turns a silent NAN into an explicit, checkable value. The last line shows why the naive comparison fails: NAN is never equal to anything, including itself.

Example · php
<?php
function safeSqrt(float $n): ?float {
    $r = sqrt($n);
    return is_nan($r) ? null : $r;
}

foreach ([16, 0, -9] as $n) {
    $r = safeSqrt($n);
    echo $n, ' -> ', $r === null ? 'undefined' : $r, "\n";
}

// Why == does not work
var_dump(sqrt(-9) == NAN);  // bool(false)

sqrt() versus hypot() and the ** operator

sqrt() and ** 0.5 agree exactly, and hypot() matches the manual Pythagorean formula while resisting overflow. The final pair shows that a round trip through sqrt() lands a few ULPs off, so an epsilon comparison is required.

Example · php
<?php
$a = 3.0; $b = 4.0;
echo sqrt($a * $a + $b * $b), "\n";  // 5
echo hypot($a, $b), "\n";            // 5 - safer for extremes

var_dump(sqrt(16) === 16 ** 0.5);    // bool(true)

// Chained float maths is not exact
var_dump(sqrt(2) * sqrt(2) == 2.0);        // bool(false)
var_dump(abs(sqrt(2) * sqrt(2) - 2) < 1e-9); // bool(true)

Discussion

  • Be the first to comment on this lesson.