Archive for PHP

How To: PHP – Roots in PHP (Square Root, Cube Root and nth Root)

To find the nth root of a number in PHP, we can use the pow(base, power) function, for example the cube root of 27 is equal to 27 raised to the power of 1/3, \sqrt[3]{27} = 27^{1/3}, since 3^3 = 27.  In general the nth root of x, \sqrt[n]{x} = x^{1/n}.

To calculate the square root of a number, we can also use the sqrt(number) function.

Example

Some example code showing how to calculate roots in PHP is below:

<?php
// Square root
echo sqrt(49) . "<br />";  // square root of 49
echo pow(49,1/2) . "<br />"; // alternative to square root of 49
echo pow(8,1/2). "<br />"; // square root of 8

// cube root
echo pow(8,1/3). "<br />"; // cube root of 8
echo pow(27,1/3). "<br />"; // cube root of 27

// higher roots
echo pow(390625,1/4). "<br />";
echo "25^4 = " . pow(25,4) . "<br />";

echo pow(1234, 1/6). "<br />";
?>

The output from this example is as follows:

7
7
2.8284271247462
2
3
25
25^4 = 390625
3.2750594908837

Comments (1)

HowTo: PHP – Raise a Number to the Power of Another (exponent in PHP)

You might need to raise a number to the power of another in a PHP script, for example 3^5 = 3 \times 3 \times 3 \times 3 \times 3 (sometimes written 3^5), or in general x^n. This may also be used with negative powers where x^{-n} = \frac{1}{x^n}.  Of course, you’d probably want to do this for more complicated examples!

PHP has a function built in to do this: x^n = pow(x,n).

Examples of ‘Power Of’

Here are some examples, which raise a number to the power of another and display the output.  In the examples, <br /> inserts a line break to display the results neatly.

<?php
echo "3^5 = " . pow(3,5) . "<br />"; // 243
echo "2^9 = " . pow(2,9) . "<br />"; // 512
// Anything raised to the power of 0 is 1:
echo "99^0 = " . pow(99,0) . "<br />"; // 1
// Negative powers:
echo "3^-1 = 1/3 = " . pow(3,-1) . "<br />"; // 1/3 = 0.3333
echo "3^-2 = 1/(3^2) = " . pow(3,-2) . "<br />"; // 1/9 = 0.1111
echo "<br />";

// Loop through 2 raised to the 0,1,2,...,10:
for($i=0;$i<=10;$i++)
{
  echo "2^" . $i . " = " . pow(2,$i) . "<br />";
}
?>

Output of the example:

3^5 = 243
2^9 = 512
99^0 = 1
3^-1 = 1/3 = 0.33333333333333
3^-2 = 1/(3^2) = 0.11111111111111

2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
2^7 = 128
2^8 = 256
2^9 = 512
2^10 = 1024

Good luck! If you have any questions about this article then please post a comment!

Leave a Comment