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?
PHP sqrt() function returns square root of the given arg number. For negative number, the function returns NAN.
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.
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.
Return Value The sqrt() function returns the square root result.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With