Calculate APR from loan, monthly payments, and amount of months

397 Views Asked by At

For some reason calculating APR is very difficult. A lot of people ask, but not a lot of great answers. I'm working on a project, where I need to calculate APR. I have already calculated what the loan is, how much the user has to pay each month, and I have the amount of months. I found a formula online, but it doesn't make a lot of sense.

function calculateAPR(loan, repayments, months) {
    var p = 1;
    var tmp = 1;
    var a = p;
    var b = 0;
    while (Math.abs(tmp) > 0.0001) {
        p = (a - b) / 2 + b;
        tmp = (loan / repayments) - (1 - Math.pow(1 + p, -months)) / p;
        if (tmp > 0) {
            a = p;
        } else {
            b = p;
        }
    }
    var apr = Math.pow((1 + p), 12) - 1;
    return apr;
}

Math.pow()'s second argument is what you want to power by an amount. Basically 1+p^12 on the third last line. Math.abs() returns the absolute value (-10 becomes 10). If I input this:

loan = 80000
repayments = 7366
months = 12

I get an APR of 20.56%. That seems correct according to the site I got the formula from, but when I input the numbers into other websites, I get no where near the same result.

Can someone explain how this formula works? Why is there a loop? Is it because of compound interest? Is there a better formula? I'm looking for any kind of help, because I can't seem to find answers that solve this programmably. Thanks.

1

There are 1 best solutions below

10
On BEST ANSWER

The loop is designed to progressively narrow the interval in which the correct apr resides. At the outset, the program assumes (arbitrarily) that the correct monthly apr, $r$ say, is between $0$ and $1$ (i.e., between $0\text{%}$ and $100\text{%}$).

The variables $a,b$ denotes the bounds on $r$, where $b \le r \le a$.

As the program progresses, the values of $a$ and $b$ are adjusted, as follows . . .

The variable $p$ is set to the middle of the known range (i.e., $p = b + (a-b)/2$).

The value $p$ is then tested to see whether it's too low or too high.

If too low, $b$ is set to $p$, and $a$ is left as is.

If too high, $a$ is set to $p$, and $b$ is left as is.

After each pass through the loop, the value of $a - b$ is half its previous value.

When $a-b$ is less than $0.0001$ (an arbitrary tolerance), the loop terminates.

Then the value of $p$ at the end is the desired $r$, which is then adjusted from a monthly rate to an annual rate in the standard way.