Saturday, August 24, 2013

Square Roots in PHP

8/24/2013

Doing square roots in PHP is really simple, all you need to do is to call the function sqrt().  Lets see some code.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//Set number you would like to take square root
$int = 9;
//Take square root
$sqrt = sqrt($int);
//Display result
echo $sqrt;


?>
As you can see, simple to do. Now lets do it in a more mathematical way using the PHP function pow(), which is the power function. pow() has two inputs, pow($base, $n). $base is the base number you will raise to the $n power. Now usually, we would use this function to calculate powers like 22 (which is 4). However, if you know your math, we can raise numbers to the power of fractions, which is the same as taking the root of numbers. Not just the square root either, we can use this to find the cube root, fourth root, any root you would like to find. Now lets see some code for finding the cube root of 729.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//Set base number and the exponent
$base = 729;
$exp = 1/3;
//Take root
$sqrt = pow($base, $exp);
//Display result
echo $sqrt;


?>
The $base is the number we will be taking the power of $exp of. This way we can use the pow() function to not only find powers of numbers but the roots as well.



Other notes:

All PHP code needs “<?php” before and “?>” after the code to run.

The double slash “//” is a comment that PHP will ignore. For bigger comments, use “/* really big comment */”.

The “$int” is a variable. Use the dollar sign in front of a meaningful variable name to create variables in PHP.

sqrt() is the function that calculates the square root of a float number.

pow($float, $exp) is the function calculates a number $float to the power of $exp.

The “echo” function prints whatever values you pass to it in the HTML of the webpage.

helpful? Share this

The Editorial Team of 4everTutorials consists of a group of PHP Professionals.

0 comments:

 

© 2014 4everTutorials. All rights resevered.

Back To Top