Calculating interest rate in PHP

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 03:53:01

You can use "Binary Search" instead of "Newton Raphson method".

function rate($month, $payment, $amount)
{
    // make an initial guess
    $error = 0.0000001; $high = 1.00; $low = 0.00;
    $rate = (2.0 * ($month * $payment - $amount)) / ($amount * $month);

    while(true) {
        // check for error margin
        $calc = pow(1 + $rate, $month);
        $calc = ($rate * $calc) / ($calc - 1.0);
        $calc -= $payment / $amount;

        if ($calc > $error) {
            // guess too high, lower the guess
            $high = $rate;
            $rate = ($high + $low) / 2;
        } elseif ($calc < -$error) {
            // guess too low, higher the guess
            $low = $rate;
            $rate = ($high + $low) / 2;
        } else {
            // acceptable guess
            break;
        }
    }

    return $rate * 12;
}

var_dump(rate(60, 1000, 20000));
// Return 0.56138305664063, which means 56.1383%

The "Binary Search" and "Newton Raphson method" are basically a guess method. It make an initial guess and improve their guess over time until it meet the acceptable guess. "Newton Raphson method" usually is faster than "binary search" because it has a better "improving guess" strategy.

The concept is simple:

We want to know r which is the interest rate. We know, N, C, and P. We don't know what is r, but let just guess any number between 0.00 to 1.00. (In this case, we assume that the interest rate cannot be over 100%).

  • Step 1: Make a random guess
  • Step 2: Plug the rate into formula,
  • Step 3: Check if the guess is too low, higher the guess, goto Step 2
  • Step 4: Check if the guess is too high, lower the guess, goto Step 2
  • Step 5: We got acceptable rate.
  • Step 6: r is monthly rate. Multiple by 12 to get annually rate.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!