Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get square root with decimal value of large integer?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading