简体   繁体   中英

Calculating Loan Interest and Duration of loan. Java

The following 2 methods are intended to calculate the length of loan(number of monthly payments that have to be paid and the interest due in the loan, respectively, given the parameters in which r is the monthly interest rate(APR), A is the loan amount(principal), P is the monthly payment and N is the number of payments that need to be made. However neither of the methods calculate correctly. How do I fix them so that they provide the number of months the payment must be made and the interest accrued?

    public static double loanLength(double r, double A, double P){         

        double N = (Math.log(1 / (1 - ((r * A) / P)))) / Math.log(1 + r);
        return N;
   }  
    public static double loanInterest(double P, double N, double A){

        double I = ((P * N) - A);
        return I;
   }

According to your example input it's just an arithmetic error.

The line double N = (Math.log(1 / (1 - ((r * A) / P)))) / Math.log(1 + r); has some calculations in it. The one that fails (or results in NaN ) is Math.log(1 / (1 - ((r * A) / P))) .

If we insert the example values: Math.log(1 / (1 - ((0.1 * 10000) / 500))) and we calculate that out:

1. Math.log(1 / (1 - ((0.1 * 10000) / 500)))
2. Math.log(1 / (1 - (1000 / 500)))
3. Math.log(1 / (1 - 2))
4. Math.log(1 / -1)
5. Math.log(-1) // <-- here happens the error

A logarithm of a number smaller/equals than 0 is not defined. So your equation is wrong

This site explains that the interest rate and payment have to be for the same period.

I guess in your case 10% is per year, while 500 is per month. So you need to divide 10 or multiply 500 by 12 to make them fit together. Otherwise, your calculation will give you the duration for a loan with 10%/500payment per month or per year (or any duration really), which can never be payed back: in every period there is 1000 interest, but only 500 payment.

Hence, log(-x) produces NaN, meaning you can never pay back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM