skip to Main Content

My code for large integer sqrt

<?php

$y2 = gmp_init('28626386478758000000000000909090904'); // Example GMP number
$sqrt = gmp_sqrt($y2);
echo "Square root is: " . gmp_strval($sqrt) . "n"; // Output the square root

?>

It gives result

Square root is: 169193340527214604

But how to get decimal part of sqrt?

2

Answers


  1. In PHP, when using the gmp_sqrt() function, you’ll only get the integer part of the square root. If you’re looking to calculate the decimal portion as well, you’ll need to use the bcmath extension, which can handle arbitrary precision numbers.

    Here’s a quick way to get that decimal part using a custom function. This method will give you a square root with a certain number of decimal places:

    <?php
    
    // Function to calculate square root with decimal precision using BCMath
    function precise_sqrt($num, $precision = 10) {
        if ($num < 0) {
            return null; // Square root of negative numbers isn't real
        }
        $estimate = bcdiv($num, '2', $precision); // Start with half the number
        $prevEstimate = '0';
    
        // Keep refining the estimate until it doesn't change
        while (bccomp($estimate, $prevEstimate, $precision) !== 0) {
            $prevEstimate = $estimate;
            $estimate = bcdiv(bcadd($estimate, bcdiv($num, $estimate, $precision)), '2', $precision);
        }
    
        return $estimate;
    }
    
    $y2 = '28626386478758000000000000909090904'; // Your large number
    $result = precise_sqrt($y2, 20); // Calculate with 20 decimal points of precision
    echo "Square root: " . $result . "n"; // Output
    
    ?>
    

    What’s happening here:

    • We start by guessing the square root (half the value) and keep refining that guess.

    • The loop continues until the new guess is very close to the previous one, with the number of decimal places controlled by the $precision argument.

    • bcadd(), bcdiv(), and bccomp() are used for calculations with large numbers.

    You can tweak the precision to get as many decimal places as you need, making this method useful when working with really large numbers like in your case.

    This approach gives you the desired square root, including the decimal portion, for large numbers in PHP!

    Login or Signup to reply.
  2. To compute the square root of an arbitrarily large number, you can use the bcsqrt() function of the BCMath extension:

    echo bcsqrt('28626386478758000000000000909090904', 20);
    

    Output:

    169193340527214604.67074165428427766793
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search