PHP Reference ยท Math Functions
PHP pow() and sqrt() functions
Reference for PHP pow(), the ** operator, sqrt() and hypot(): integer versus float results, overflow to float, negative roots giving NAN and cube roots.
pow() raises a number to a power and sqrt() returns the square root. The ** operator does the same job as pow(), and is usually shorter to read. sqrt() always returns a float; pow() returns an integer when both operands are integers, the exponent is not negative, and the result fits into an integer.
Neither function throws on bad input. The square root of a negative number is NAN, and an integer power that is too large silently becomes a float.
<?php echo 2 ** 10; // 1024 echo pow(2, 0.5); // 1.4142135623731 echo sqrt(81); // 9
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
pow(mixed $num, mixed $exponent): int|float|object sqrt(float $num): float
| Name | Description |
|---|---|
$num |
The base for pow(); the value whose square root is wanted for sqrt(). |
$exponent |
The power to raise $num to. May be negative or fractional. |
Return value: pow() returns an int when the base and exponent are integers, the exponent is not negative and the result fits; otherwise a float. sqrt() returns a float, or NAN for negative input.
Usage notes
**andpow()are equivalent. The operator is right-associative and binds tighter than unary minus:-2 ** 2is-4.- Negative exponents give floats:
2 ** -1is0.5. - Overflow becomes a float, not an error. If you need exact huge integers, use BCMath (
bcpow()) or GMP. NANfor impossible results. A negative base with a fractional exponent ((-8) ** (1/3)) isNAN. PHP has nocbrt(); take the root of the absolute value and restore the sign. Check withis_nan().- Exactness: for perfect squares
sqrt()is exact, butsqrt($n) ** 2for other values may differ from$nin the last digits. - Integer square root: use
(int) floor(sqrt($n)). Floats lose precision above 2^53, so for huge integers use GMP'sgmp_sqrt()or BCMath'sbcsqrt(). hypot($a, $b)computes the square root ofa*a + b*bwithout intermediate overflow.0 ** 0is1.