Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo 2 ** 10;        // 1024
echo pow(2, 0.5);    // 1.4142135623731
echo sqrt(81);       // 9

Try it

PHP Powers and roots

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.

PHP Distance, cube roots and compound growth

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

PHP
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

  • ** and pow() are equivalent. The operator is right-associative and binds tighter than unary minus: -2 ** 2 is -4.
  • Negative exponents give floats: 2 ** -1 is 0.5.
  • Overflow becomes a float, not an error. If you need exact huge integers, use BCMath (bcpow()) or GMP.
  • NAN for impossible results. A negative base with a fractional exponent ((-8) ** (1/3)) is NAN. PHP has no cbrt(); take the root of the absolute value and restore the sign. Check with is_nan().
  • Exactness: for perfect squares sqrt() is exact, but sqrt($n) ** 2 for other values may differ from $n in the last digits.
  • Integer square root: use (int) floor(sqrt($n)). Floats lose precision above 2^53, so for huge integers use GMP's gmp_sqrt() or BCMath's bcsqrt().
  • hypot($a, $b) computes the square root of a*a + b*b without intermediate overflow.
  • 0 ** 0 is 1.