java compound interest with contributions formula - java

I am currently trying to develop a compound interest calculator that includes monthly contributions. I have successfully been able to get the compound interest calculation working without the monthly contributions using the following line of code, but cannot figure out what the formula should be when adding monthly contributions.
double calculatedValue = (principalValue * Math.pow(1 + (interestRateValue/numberOfCompoundsValue), (termValue * numberOfCompoundsValue)));
When trying to get the calculated value with contributions I changed the way this is done. See the following code how I approached this.
//The starting principal
double principalValue = 5000;
//Interest rate (%)
double interestRateValue = 0.05;
//How many times a year to add interest
int numberOfCompoundsValue = 4;
//The number of years used for the calculation
double termValue = 30;
//The monthly contribution amount
double monthlyContributionsValue = 400;
//How often interest is added. E.g. Every 3 months if adding interest 4 times in a year
int interestAddedEveryXMonths = 12/numberOfCompoundsValue;
//The total number of months for the calculation
int totalNumberOfMonths = (int)(12 * termValue);
for(int i = 1; i <= totalNumberOfMonths; i++)
{
principalValue += monthlyContributionsValue;
if(i % interestAddedEveryXMonths == 0)
{
principalValue += (principalValue * interestRateValue);
}
}
I figured this should do what I am after. Every month increase the principal by the contribution amount and if that month equals a month where interest should be added then calculate the interest * the interest rate and add that to the principal.
When using the values above I expect the answer $355,242.18 but get $10511941.97, which looks better in my bank account but not in my calculation.
If anyone can offer me some help or point out where I have gone wrong that would be much appreciated.
Thanks in advance

Your problem is here:
principalValue += (principalValue * interestRateValue);
You're adding a full year's interest every quarter, when you should be adding just a quarter's interest. You need to scale that interest rate down to get the right rate.
Here's an example:
class CashFlow {
private final double initialDeposit;
private final double rate;
private final int years;
private final double monthlyContribution;
private final int interestFrequency;
CashFlow(double initialDeposit, double rate, int years,
double monthlyContribution, int interestFrequency) {
if ( years < 1 ) {
throw new IllegalArgumentException("years must be at least 1");
}
if ( rate <= 0 ) {
throw new IllegalArgumentException("rate must be positive");
}
if ( 12 % interestFrequency != 0 ) {
throw new IllegalArgumentException("frequency must divide 12");
}
this.initialDeposit = initialDeposit;
this.rate = rate;
this.years = years;
this.monthlyContribution = monthlyContribution;
this.interestFrequency = interestFrequency;
}
public double terminalValue() {
final int interestPeriod = 12 / interestFrequency;
final double pRate = Math.pow(1 + rate, 1.0 / interestPeriod) - 1;
double value = initialDeposit;
for ( int i = 0; i < years * 12; ++i ) {
value += monthlyContribution;
if ( i % interestFrequency == interestFrequency - 1 ) {
value *= 1 + pRate;
}
}
return value;
}
}
class CompoundCalc {
public static void main(String[] args) {
CashFlow cf = new CashFlow(5000, 0.05, 30, 400, 3);
System.out.println("Terminal value: " + cf.terminalValue());
}
}
with output:
run:
Terminal value: 350421.2302849443
BUILD SUCCESSFUL (total time: 0 seconds)
which is close to the $355k value you found.
There are a number of different conventions you could use to get the quarterly rate. Dividing the annual rate by 4 is a simple and practical one, but the pow(1 + rate, 1 / 4) - 1 method above is more theoretically sound, since it's mathematically equivalent to the corresponding annual rate.

After some brief testing I've come to the conclusion that either you have:
miscalculated the value you want ($355,242.18)
OR
incorrectly asked your question
The calculation you've described that you want ($5000 start + $400 monthly contributions for 30 years + interest every 3 months) is found by the code you've provided. The value that it gives ($10,511,941.97) is indeed correct from what I can see. The only other suggestions I can offer are to only use double if you need to (for example termValue can be an int) AND when ever you know the value is not going to change (for example interestRateValue) use final. It will help avoid any unforeseen error in larger programs. I hope this helps you figure out your interest calculator or answers any questions you have.

static void Main(string[] args)
{
double monthlyDeposit;
double rateOfInterest;
double numberOfCompounds;
double years;
double futureValue = 0;
double totalAmount = 0;
Console.WriteLine("Compound Interest Calculation based on monthly deposits");
Console.WriteLine("Monthly Deposit");
monthlyDeposit = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Rate Of Interest");
rateOfInterest = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Number of Compounds in a year");
numberOfCompounds = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Number of year");
years = Convert.ToDouble(Console.ReadLine());
futureValue = monthlyDeposit;
for (int i = 1; i <= years * 12; i++)
{
totalAmount = futureValue * (1 + (rateOfInterest / 100) / 12);
if (i == years * 12)
futureValue = totalAmount;
else
futureValue = totalAmount + monthlyDeposit;
}
Console.WriteLine("Future Value is=" + futureValue);
Console.ReadLine();
}
//Output
Compound Interest Calculation based on monthly Deposits
Monthly Deposit
1500
Rate Of Interest
7.5
Number of Compounds in a year
12
Number of year
1
Future Value is=18748.2726237313

Related

Loops, which to use, and how to stop it

My problem is: Suppose that one credit hour for a course is $100 at a school and that rate increases 4.3% every year. In how many years will the course’s credit hour costs tripled?
The rewrote this simple code many times, but just can't seem to get it.
I think i'm going about this the wrong way..
import java.util.Scanner;
public class MorenoJonathonCreditHourCostCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double cost = 100;
int years=0;
double sum=200;
double total;
while (cost >= sum) {
total = cost + 4.03;
++years;
}
System.out.println("The tuition will double in " + years + " years");
}
}
A rate increase of 4.3% means that in every step, the value is 4.3% bigger than the previous value. This can be described by the following formula:
V_n+1 = V_n + (V_n * 4.3%)
V_n+1 = V_n + (V_n * 0.043)
V_n+1 = V_n * (1 + 0.043)
V_n+1 = V_n * 1.043
In Java this boils down to simply cost *= 1.043;
You first stated " In how many years will the course’s credit hour cost tripled", but in your program you actually check for when it has doubled.
I assume you want to calculate the triple cost, so your program should now look something like this:
public static void main(String[] args) {
double cost = 100;
double tripleCost = 3 * cost;
int years = 0;
while(cost < tripleCost) {
cost *= 1.043;
years++;
}
System.out.println("It took " + years + " years.");
}
Which gives the following output:
It took 27 years.
I am not sure why you are adding to cost since it is a multiplication function:
FV(future value) = PV(present value) (1+r)^n
300 = 100(1.043)^n where you are looking for 'n'
Set up a while loop that operates while the future value is under 300 and adds to 'n'.

How can I turn this compound value function into a for-loop?

Okay so I am new to Java. I have a program that calculates the compound value after asking the user for a savings amount and an annual interest rate. I'm having trouble getting it into a for loop but I feel like I'm somewhat close? The hard part in my mind is understanding how to get the last months total into the new calculation.
Here's my formula for the compound value currently:
firstMonth = savingAmount * (1 + monthlyInterestRate);
secondMonth = (savingAmount + firstMonth) * (1 + monthlyInterestRate);
thirdMonth = (savingAmount + secondMonth) * (1 + monthlyInterestRate);
fourthMonth = (savingAmount + thirdMonth) * (1 + monthlyInterestRate);
fifthMonth = (savingAmount + fourthMonth) * (1 + monthlyInterestRate);
sixthMonth = (savingAmount + fifthMonth) * (1 + monthlyInterestRate);
It is ugly obviously and it should be in a for-loop. Again the savingAmount is user input and the annualInterestRate is user input. The the monthlyInterestRate is annualInterestRate/12.
Here is the for-loop I have so far.
for (int i = 1; i <= 6; i++ );
{
sixthMonth = savingAmount * Math.pow(1+monthlyInterestRate, 6);
}
I am still learning for-loops but doesn't my code say it adds up while it is less than or equal to 6? And while those are true to do the formula I provided. No you don't have to answer the question but if you could lead me in the right direction that'd be great. So how would I start to convert it? Feel free to ask for more info if needed.
Try this:
for (int i = 1; i <= 6; i++) {
monthAmount = (savingAmount + monthAmount) * (1 + monthlyInterestRate);
}
This should get you to the same answer.
You were on the right track, but this will allow you to use the previous months amount in the formula. This code will also work for however long you want the loop to run for.
I would actually recommend using the compound interest formula A = P (1 + r/n) ^ nt.
A - final amount with compound growth
P - principal investment
r - annual interest rate
n - number of times the interest is compounded per time period
t - number of time periods compounded
So you could then reduce all of this to:
amount = savingAmount * Math.pow(1 + monthlyInterestRate/timesCompoundedPerMonth,
timesCompoundedPerMonth * monthsCompounded);
Compound Interest Formula - Explained
I would recommending storing the amounts in a list for easy lookup if you want to see how much savings you will have at each month.
public static void main(String args[]) {
double savingsAmount = 543.23;
double annualInterestRate = 0.85; // %
double monthlyInterestRate = annualInterestRate / 12;
List<Double> savings = new ArrayList<Double>();
savings.add(savingsAmount); // month 0
int monthsInTheFuture = 6;
double compoundInterest = 1 + monthlyInterestRate;
for (int i = 1; i <= monthsInTheFuture; i++) {
double previousSavings = savings.get(i-1);
double nextSavings = previousSavings * compoundInterest;
savings.add(nextSavings);
}
System.out.println(savings);
}

Recursive method for loan calculation

I'm trying to write a recursive method that takes 3 parameters (a loan amount, an interest rate, and a monthly payment). The interest is compounded monthly. The goal is to find out how many months it will take to pay off the loan completely. Here is the code I have so far:
public static double loanLength(double loan, double interest, double payment) {
if (payment > loan + loan * interest) {
return 0;
} else {
double completeLoan = loan + (loan * interest);
double stillOwe = completeLoan - payment;
if (stillOwe <= 0) {
return 1;
} else {
return 1 + (loanLength(stillOwe, interest, payment));
}
}
Examples of EXPECTED returns include:
loanLength(1000, 0.10, 200) is paid off in 6 months
loanLength(0, 0.90, 50) is 0 months
But my returns look like:
loanLength(1000, 0.10, 200): 7 months
loanLength(0, 0.90, 50): 0 months
My second test works fine, but my first one is just 1 integer above what it should be. I cannot figure out why. Any help is appreciated.
public static int loanLength(double loan, double interestAPR, double payment) {
if (loan <= 0) {
return 0;
}
double monthlyInterest = interestAPR / (12 * 100);
double compounded = loan * (1 + monthlyInterest);
return 1 + loanLength(compounded - payment, interestAPR, payment);
}
public static void main(String[] args) {
System.out.println(loanLength(0, 0.90, 50)); // 0
System.out.println(loanLength(1000, 10.0, 200)); // 6
System.out.println(loanLength(1000, 0.1, 200)); // 6 (FWIW)
}
Please note that interest APR is expressed as is, i.e. a $10,000 loan at 10% APR and $500 monthly payments is calculated as
loanLength(10000, 10.0, 500);
If 0.10 = 10% APR, then change this line
double monthlyInterest = interestAPR / 12;

Confusion on compound interest arithmetic with Java

I hope this isn't a horrifically obvious question, but I'm new to Java and I've been creating a compound interest calculator. I wan't to take all the values that the user inputs and compute them.
P = present value,
r = rate,
m = times compounded in a year,
t = years compounded.
A = the amount at the end of the term
A is what I'm looking for. The formula for compound interest is
A = P(1+r/m)^mt.
A = Math.pow((P*(1+r/m)),m*t);
System.out.println("The amount(A) equals "+A);
I feel that I may know why the computation isn't working right, but I don't know the right way.
This should solve your problem
double amount,Principal ;
int r,m,t;
Amount = Principal * Math.pow( (1+(r/m)) , m*t );
System.out.println("The amount(A) equals "+amount);
I believe you formula is incorrect. You need to write it like:
public static void main(String[] args) {
int p = 100;
int t = 5;
int r = 10;
int m = 2;
double amount = p * Math.pow(1 + (r / m), m * t);
double interest = amount - p;
System.out.println("Compond Interest is " + interest);
System.out.println("Amount is " + amount);
}

Calculating Compound Interest without math.pow in java

I need to calculate the monthly compounding interest in a savings account that is getting a monthly deposit. The variables I have to work with:
monthly savings ( Eg. I deposit $125.75 each month)
months (Eg. I deposit the same for 15 months)
APR (the ANNUAL interest is 5.65%)
Now I need to calculate the total savings amount, which for the given numbers here, the final answer should be $1958.88.
In essence, I am working with A = P(1 + r/12)^(12*t), where P is the amount I deposit * months, r is the APR, and t is the months/12 to get the "how many years"
The catch here is that I can not use the math.pow() as a requirement on the assignment, so my best guess is that I am to calculate it with a for/while loop similar to the following:
public static void main(String[] args)
{
double monthlySavings = 125.75;
double APR = 5.65;
int months = 15;
int monthCount = 0;
double totalSavings = 0;
while (monthCount < months)
{
totalSavings += monthlySavings + (1+APR/12/100);
mothCount++;
}
System.out.printf("Your total savings will be $%.2f\n", totalSavings);
}
The above code is NOT the correct solution, but its the closest i've come. The problem is that I am applying the interest to the monthly savings each time before it accumulates to the total. eg. it adds 125.75*interest for 15 deposits. What it SHOULD do is start with 125.75*interest then add 125.75, and then take the interest of the amount you have total so far, then add 125.75 and take the interest of the total amount again, and so on for the amount of months.
This is probably a lot easier than I am making it out to be, but I have tried for hours with adding different placeholder variables, but I am lacking some crucial concept, please help!
A loop for the number of months
for (int monthNumber = 0; monthNumber < numberOfMonths; monthNumber++)
{
}
then for each each month, add the interest then add the monthly savings. In that order, the other way around you end up with interest on money you just deposited, which is wrong.
totalSavings *= (APR / 12 / 100); //Although I would have separate variable for this
totalSavings += monthlySavings;
you don't really need to keep a month count but I prefer for loops.
After re-reading my question, I had an epiphany.. As I originally thought, the answer was a lot easier than I was making it out to be.
public static void main(String[] args)
{
double monthlySavings = 125.75;
double APR = 5.65;
int months = 15;
int monthCount = 0;
double placeHolder = 0;
double totalSavings = 0;
while (monthCount < months)
{
placeHolder += monthlySavings;
totalSavings = placeHolder * (1+APR/12/100);
placeHolder = totalSavings;
monthCount++;
}
System.out.printf("Your total savings will be $%.2f", totalSavings);
}

Categories