2012-06-28 12 views
5

PHPでN番目のルートを探しています。非常に大きな数値でこれを行う必要があり、窓の計算機は2を返します。以下のコードで私たちは1を得ています。PHPのbcmathでN番目のルートを計算する

echo bcpow(18446744073709551616, 1/64); 
+2

bcpow()は整数指数のみを受け付けるため、機能しません。 64番目のルートが必要な場合は、代わりに6つの平方根を実行します。 – Niko

答えて

10

まあ、あなたがこの機能を使用する必要がありますPHPとBC libには、いくつかの制限があり、インターネット上で検索した後、私はこのinteresting article/code:

を見つけたようだ:

<?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"); 

?> 

・ホープ、この役に立った...

+2

ありがとう!魅力的な作品!私はあなたに+10を与えるだろうが、私は+1しかできない:P –

関連する問題