Home  >  Article  >  Daily Programming  >  How to find the square root of a number in PHP

How to find the square root of a number in PHP

藏色散人
藏色散人Original
2019-01-21 15:38:4510341browse


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.

How to find the square root of a number in PHP

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.

How to find the square root of a number in PHP

# 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:

How to find the square root of a number in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn