Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square root in PHP

Tags:

php

sqrt

Why is the output of sqrt not an integer for "16" in PHP?

Example

php > $fig = 16;
php > $sq = sqrt($fig); //should be 4
php > echo $sq;
4
php > echo is_int($sq);            // should give 1, but gives false
php > 

I feel that the problem is in the internal presentation which PHP hides similarly as Python. How can you then know when the given figure is integer after taking a square root?

So how can you differentiate between 4 and 4.12323 in PHP without using a regex?

like image 371
Léo Léopold Hertz 준영 Avatar asked Oct 31 '09 14:10

Léo Léopold Hertz 준영


People also ask

How do you write square root in PHP?

PHP sqrt() function returns square root of the given arg number. For negative number, the function returns NAN.

How can I get cube root in PHP?

Method 1: Using exponent operator of PHP The exponential (**) operator of PHP can be used to calculate the cube root of a number. Consider the following example. <? php $x = 64; $y = 125; $x1 = $x**(1/3); $y1 = $y**(1/3); echo "Cube root of $x is $x1.

What is square root in programming?

The sqrt() function takes a single argument (in double ) and returns its square root (also in double ). [Mathematics] √x = sqrt(x) [In C Programming] The sqrt() function is defined in math.

What is the return of the function sqrt?

Return Value The sqrt() function returns the square root result.


1 Answers

According to the PHP manual, float sqrt ( float $arg ), sqrt() always returns a float. Using the is_int() function won't solve the problem because it checks the datatype and returns a failure.

To get around this, you can test it by using modulus instead: (must be fmod() for floating point modulus and not the % operator for integer modulus)

if (fmod(sqrt(16), 1) == 0) {
   // is an integer
}

If you are using PHP 5.2.0 or later, I believe this would also work, but I haven't used it in this type of circumstance to be certain:

$result = sqrt(16);
if (filter_var($result, FILTER_VALIDATE_INT)) {
    // is an integer
}
like image 189
Jason Avatar answered Sep 29 '22 10:09

Jason