Home > Article > Daily Programming > How to find the square root of a number in PHP
Use a PHP program to calculate and return the square root of a given number, so first you need to understand what the square root of a number is. The square root, also called the quadratic root, is expressed as [±√ ̄], among which the square root of a non-negative number is called an arithmetic square root. A positive number has two real square roots, which are opposites of each other, and a negative number has two conjugate pure imaginary square roots.
Recommended reference study: "PHP Tutorial"
Formula definition:
If a number x, it The square of is equal to a, that is, x²=a,
If the square of x is equal to a, then x is called the square root of a, that is, √a ̄=x
as shown in the figure below.
# Now we will use PHP code examples to introduce to you the PHP method of finding the square root of a number.
The code example is as follows:
<?php //PHP程序来计算并返回给定数字的平方根 function my_sqrt($n) { $x = $n; $y = 1; while ($x > $y) { $x = ($x + $y)/2; $y = $n/$x; } return $x; } print_r(my_sqrt(16)."<br>"); print_r(my_sqrt(25)."<br>");
In the above code, we create a my_sqrt method and implement it with a while loop. Here we calculate the square root of 16 and 25.
The calculation results are shown in the figure below:
This article is an introduction to the method of finding the square root of a number in PHP. It is simple and easy to understand. In fact, it is also a flexible application of the basic knowledge of PHP algorithms. I hope it will be helpful to friends in need!
The above is the detailed content of How to find the square root of a number in PHP. For more information, please follow other related articles on the PHP Chinese website!