sqrt
sqrt($num)
Returns the square root of a number, always as a float. For a negative number it returns the special value NAN (not a number).
Parameters
- $num – the number to take the root of.
Examples
echo sqrt(16); // 4 // the result is always a float var_dump(sqrt(16)); // float(4) echo round(sqrt(2), 4); // 1.4142 // a negative number var_dump(is_nan(sqrt(-1))); // bool(true) // the distance between the points [1, 2] and [4, 6] echo sqrt(pow(4 - 1, 2) + pow(6 - 2, 2)); // 5 // the hypotenuse of a right triangle echo hypot(3, 4); // 5 // is the number the square of an integer? $number = 49; $root = (int) round(sqrt($number)); var_dump($root * $root === $number); // bool(true) // the cube root echo round(pow(27, 1 / 3), 10); // 3
Things to watch out for
- It returns a float even when the root is a whole number. The strict comparison sqrt(16) === 4 is therefore false.
- For a negative number it returns NAN. Only is_nan() recognizes this value, a comparison with anything (even with itself) returns false.
- The result is often only approximate. Round it with round() before comparing.
- Other roots are calculated by pow() with a fractional exponent.