calculations can't figure out
<p>Problem:</p>

<p>Function not always retuning the right result
APR(credit_amount, credit_price, days, number_of_payments);</p>

<p>APR(1000, 1000, 1000, 1000); //Result: 78.76344% GOOD</p>

<p>APR(1000, 200, 365, 6); //Result 37.66323% should be : 37.57%</p>

<p>APR(1000, 200, 365, 1); //Result 20% GOOD</p>

<p>APR(1000, 200, 365, 2); //Result 27.83974% should be : 27.81%</p>

<p>APR(1000, 30, 30, 30); //Result 101.23434% should be : 99.97%</p>

<p>APR(1000, 30, 20, 20); //Result 180.70707% should be : 178.2%</p>

<p>APR(1000, 30, 10, 10); //Result 616.78% GOOD</p>

<p>APR(1000, 30, 9, 9); //Result 772.65015% should be : 766.8%</p>

<p>Function:</p>

<pre><code>function APR($credit, $price, $days, $payments) {

$repaymentTotal = 0;
$bsMinB = -0.999999999999;
$bsMaxB = PHP_INT_MAX;
$APRRate = 1;
$attempts = 0;
$precision = 5;
$err = false;

    if($credit&gt;0 &amp;&amp; $price&gt;0 &amp;&amp; $days&gt;0 &amp;&amp; $payments&gt;0) {

        $m = ($credit+$price)/$payments;

        for($i=1;$i&lt;=$payments;$i++) {

            $c['paymentnumber'] = $i;
            $c['amount'] = $m;
            $p[] = $c;

        }


        while(round($repaymentTotal, $precision) != $credit) {

            if($attempts&gt;=1000 || (($bsMaxB==$bsMinB) &amp;&amp; ($bsMaxB==$APRRate)))
                break;
                $attempts++;

            if($attempts&gt;1){

                if($repaymentTotal&lt;$credit) 

                    $bsMaxB = $APRRate;

                else

                    $bsMinB = $APRRate;
                    $APRRate = $bsMaxB - ($bsMaxB - $bsMinB)/2;

            }

            $repaymentTotal = 0;

            foreach($p as $payment) {

                $periods = ($days/$payments)*($payment['paymentnumber']/365);
                $rt = pow((float) 1+$APRRate, $periods);

                $repaymentTotal += $payment['amount'] / $rt;

            }
        }

        $result = round($APRRate*100, $precision);

    } else {
        $err = 'not all set';
    }

return ($err) ? ($err) : ($result);}
</code></pre>

<p>It always returns the right result if number_of_payments = 1.</p>

<p>Any ideas ?</p>
