dongliao1949 2012-06-28 10:43
浏览 51
已采纳

用PHP中的bcmath计算第N个根

We are looking for the Nth root in PHP. We need to do this with a very large number, and the windows calculator returns 2. With the following code we are getting 1. Does anybody have an idea how this works?

echo bcpow(18446744073709551616, 1/64);
  • 写回答

2条回答 默认 最新

  • dqmhgz5848 2012-06-28 11:25
    关注

    Well it seems that PHP and the BC lib has some limits, and after searching on the internet i found this interesting article/code:

    So you should use this function:

    <?php
    
    function NRoot($num, $n) { 
        if ($n<1) return 0; // we want positive exponents 
        if ($num<=0) return 0; // we want positive numbers 
        if ($num<2) return 1; // n-th root of 1 or 2 give 1 
    
        // g is our guess number 
        $g=2; 
    
        // while (g^n < num) g=g*2 
        while (bccomp(bcpow($g,$n),$num)==-1) { 
            $g=bcmul($g,"2"); 
        } 
        // if (g^n==num) num is a power of 2, we're lucky, end of job 
        if (bccomp(bcpow($g,$n),$num)==0) { 
            return $g; 
        } 
    
        // if we're here num wasn't a power of 2 :( 
        $og=$g; // og means original guess and here is our upper bound 
        $g=bcdiv($g,"2"); // g is set to be our lower bound 
        $step=bcdiv(bcsub($og,$g),"2"); // step is the half of upper bound - lower bound 
        $g=bcadd($g,$step); // we start at lower bound + step , basically in the middle of our interval 
    
        // while step!=1 
    
        while (bccomp($step,"1")==1) { 
            $guess=bcpow($g,$n); 
            $step=bcdiv($step,"2"); 
            $comp=bccomp($guess,$num); // compare our guess with real number 
            if ($comp==-1) { // if guess is lower we add the new step 
                $g=bcadd($g,$step); 
            } else if ($comp==1) { // if guess is higher we sub the new step 
                $g=bcsub($g,$step); 
            } else { // if guess is exactly the num we're done, we return the value 
                return $g; 
            } 
        } 
    
        // whatever happened, g is the closest guess we can make so return it 
        return $g; 
    }
    
    echo NRoot("18446744073709551616","64");
    
    ?>
    

    Hope this was helpful ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c