Compound Interest Calculator

By Sheldon L Published at 2020-03-31 Updated at 2020-03-31


Different Ways to Calculate Compound Interest, Got Different Result

/**

input:
  P - Principal dollar loan         in dollars;
  Y - make over Y years to pay      in years;
  R - Interest compounded monthly   in %/year;

output:
  payment - monthly payments        in dolars/month;

  // Method 1
  M   = Y * 12
  r   = R/100/12
  Pm  = P/M
  Ttl = Pm*(1+r) + Pm*(1+r)^2 + ... + Pm*(1+r)^M
      = Pm*(1+r) * (1 + (1+r) + (1+r)^2 + ... + (1+r)^(M-1))
      = Pm*(1+r) * (1 - (1+r)^M) / r
  payment1 = Ttl / M

  // Method 2
  M   = Y * 12
  r   = R/100/12
  payment2 = P * r / (1 - (1+r)^(-M))

  // Method 3
  M   = Y * 12
  r   = R/100/12
  Ttl = P(1 + r)^{nt}
  payment3 = Ttl / M

 */

class CarLoan {
  public static void main(String[] args) {
    double P, Y, R;
    P = Double.parseDouble(args[0]);
    Y = Double.parseDouble(args[1]);
    R = Double.parseDouble(args[2]);

    int M = (int) (Y * 12);
    double r = R / 100 / 12;

    // Method 1
    double Pm  = P/M;
    double Ttl = Pm * (1+r) * (Math.pow((1+r), M) - 1) / r;
    double payment1 = Ttl / M;

    // Method 2
    double payment2 = P * r / (1 - Math.pow((1+r), -M));

    // Method 3
    double payment3 = P * Math.pow((1 + r), M) / M;

    System.out.println(payment1 + ", " + payment2 + ", " + payment3);
  }
}