大整数的小数值如何求平方根?

问题描述 投票:0回答:1

我的大整数 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

?>

它给出了结果

Square root is: 169193340527214604

但是如何得到sqrt的小数部分呢?

php
1个回答
0
投票

在 PHP 中,使用

gmp_sqrt()
函数时,您只能得到平方根的整数部分。如果您还想计算小数部分,则需要使用
bcmath
扩展,它可以处理任意精度的数字。

这是使用自定义函数获取小数部分的快速方法。此方法将为您提供具有一定小数位数的平方根:

<?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

?>

这里发生了什么:

  • 我们首先猜测平方根(值的一半)并不断完善该猜测。

  • 循环继续,直到新的猜测非常接近前一个,小数位数由 $ precision 参数控制。

  • bcadd()、bcdiv()、bccomp()用于大数计算。

您可以调整精度以获得所需的小数位数,这使得此方法在处理像您的情况这样非常大的数字时非常有用。

对于 PHP 中的大数,此方法可为您提供所需的平方根,包括小数部分!

© www.soinside.com 2019 - 2024. All rights reserved.