I'm trying to calculate the future investment amount in Java.
My program runs, but it's not giving me the correct answer.
If the
investmentAmount is 1000.56,
interest rate is 4.25, and
number of years is 1,
the answer should be $1043.92.
The formula we have to use is futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) ^ numberOfYears * 12
Below is my class
// Import Java Scanner
import java.util.Scanner;
public class Ex_2_21 {
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter investment amount, annual interest rate, and number of years
System.out.println("Enter investment amount:");
System.out.println("Enter annual interest rate:");
System.out.println("Enter number of years:");
float investmentamount = input.nextFloat();
float interestrate = input.nextFloat();
float numberofyears = input.nextFloat();
float years = numberofyears * 12;
//Formula to calculate the accumulated value
float futureInvestmentValue = (float) (investmentamount * Math.pow((years), 1 + interestrate));
//Print result
System.out.println("The accumulated value is " + futureInvestmentValue);
}
}
On top of what #Luiggi said, did you consider that if it is 4.25 interest rate, that is 425% interest rate, what you want is 1 + 0.0425
You're using years (equal to years * 12) when you mean months, and you're not using monthly interest rate at all. Divide annual interest rate (as entered) by 12 to get monthly interest rate (and also make sure it's a fraction, not a bare percentage, so if they're entering 4.25 it needs to be divided by 100 to get .0425), and introduce a new variable for total month duration. Then (as Luiggi notes) swap the argument order.
float futureInvestmentValue = (float) (investmentAmount * Math.pow(1 + monthlyInterestRate, months));
Here's the problem:
Math.pow((years), 1 + interestrate)
It should be
Math.pow(1 + interestrate, years)
As noted in Math#pow(double a, double b):
Parameters:
a - the base
b - the exponent
Returns
The value ab
There are two problems in the above given Java program:
Lack of problem understanding (kindly, take this suggestion in a positive interest. If we, understand the problem correctly, we are very much near to its correct programming solution.)
Formula for future investment value (A) is as follows:
a) Compounded annually:
A = P*(1+R)^N
Where, A = Future value, P = Original amount invested, R = Interest rate (given as %, in calculation use as R/100), N = Time period for which compound interest rate is applied (in years)
b) Compounded monthly:
A = P*(1+(R/12))^(N*12)
Where, A = Future value, P = Original amount invested, R = Monthly interest rate (given as %, in calculation use as R/100, it is not annual interest rate), N = Time period for which compound interest rate is applied (in years)
As per values of given sample problem, we find in order to calculate future investment value, we should be using formula (b).
So, w.r.t above given Java program, to incorporate this correction we need to simply add one more statement after the interestrate variable declaration line:
interestrate = interestrate / (100 * 12);
Second problem is lack of understanding of Java programming language constructs / logical error by ignorance. Whatever is the case; it does not matter. Technically, it is a programming error and thus it needs rectification.
As already suggested above by Luiggi Mendoza, in Java programming language if we want to express mathematical expression A^B then we have to use java.lang.Math.pow() method with following syntax:
public static double pow(double A, double B)
So, again w.r.t above given Java program, to incorporate this second correction we have to simply correct the line which declares the futureInvestmentValue variable and using the Math.pow() method; as follows:
float futureInvestmentValue = (float) (investmentamount * Math.pow(1 + interestrate, years));
Incorporating these two corrections, we make our solution correct. Based on the principle of GIGO (Garbage In Garbage Out, Gold In Gold Out) we will definitely get correct and exact answer to our any sample problem given values; as expected.
Happy Programming.
Related
Background: doing a budget portfolio program and I am trying to add in a compound interest calculator for a client's savings. Running into some problems here.
So here is the formula I currently have.
double comprinc= 25*(Math.pow((1+.05/12),(12*year)));
double futurev = saving1*(Math.pow((1+.05/12),((12*year)-1))/(.05/12));
This is the following formula broken down into two halves
Total = [ P(1+r/n)^nt ] + [ PMT * (((1 + r/n)^nt - 1) / (r/n)) ]
or
Total = comprinc + futurev
P= principle =25
r= rate=.05
n= number of time interest is compounded
t= the number of years =5( have year currently set to 5)
PMT= initial savings=saving1=25
The problem is that I am testing this against an official compound interest calculator
and the answers I'm getting are no where close.
For example the answer that my program reads out is $7700.28 after 5 years should be $1739.32
I think the key is the -1 is not part of the exponent. I am also trying to simplify here, by reducing calculations and parentheses.
double intPerPeriod = .05/12;
double numPeriods = 12*year;
double comprinc= 25*(Math.pow(1+intPerPeriod,numPeriods));
double futurev = saving1*(Math.pow(1+intPerPeriod,numPeriods)-1)/intPerPeriod;
My while statement just doesn't seem to make sense to me, even though it works.
I want it to calculate the interest only as long as the countYears is less than the timeLimit....so if I set timeLimit to 5, it should only calculate 5 years worth of interest but the way I read the current while statement, it doesn't seem to say that. Maybe I am just reading it wrong?
public class RandomPractice {
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
double intRate, begBalance, balance;
int countYears, timeLimit;
System.out.println("Please enter your current investment balance.");
begBalance = Keyboard.nextDouble();
System.out.println("Please enter your YEARLY interest rate (in decimals).");
intRate = Keyboard.nextDouble();
System.out.println("Please enter how long (in years) you would like to let interest accrue.");
timeLimit = Keyboard.nextInt();
balance = begBalance * (1 + intRate);
countYears = 0;
/* The way I read this while statement is as follows
* "While countYears is GREATER than the timeLimit...calculate the balance"
* This makes no logical sense to me but I get the correct output?
* I want this code to calculate the investment interest ONLY as long as
* countYears is LESS than timeLimit **/
while (countYears >= timeLimit)
{
balance = balance + (balance * intRate);
countYears++;
}
System.out.println(balance);
}
}
That code you have, as it stands, does not generate the correct data, my transcript for eight years at one percent per annum follows:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
101.0
In other words, only one year of interest is added rather than eight years.
So either your compiler is totally screwy, your code is not what you think it is, or whatever test data and/or method you're using to check the interest calculation is lacking somewhat.
First, as you foreshadowed, you need to change the condition to be countYears < timeLimit.
In addition, you also need to remove the initial interest calculation before the loop since this would mean you'd get a full year's interest as soon as you deposit the money. With those two changes:
balance = begBalance;
while (countYears < timeLimit) {
balance = balance + (balance * intRate);
countYears++;
}
and you then get the correct value of:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
108.28567056280801
Your loop isn't being executed at all if you switch it to <= it will be correct.
Right now your output is what is calculated outside of the loop.
I need a java calculation for simple interest to compound interest, i have the amount of years,the principle amount and the simple interest rate. I cant find a calculation for it.
For future reference this site can be found by googling 'compound interest formula'
The formula for annual compound interest is A = P (1 + r/n) ^ nt
Where:
A = the future value of the investment/loan, including interest
P = the principal investment amount (the initial deposit or loan amount)
r = the annual interest rate (decimal)
n = the number of times that interest is compounded per year
t = the number of years the money is invested or borrowed for
Example:
If an amount of $5,000 is deposited into a savings account at an annual interest rate of 5%, compounded monthly, the value of the investment after 10 years can be calculated as follows...
P = 5000
r = 0.05
n = 12
t = 10
If we plug those figures into the formula, we get:
A = 5000 (1 + 0.05 / 12) ^ 12(10) = 8235.05.
So, the investment balance after 10 years is $8,235.05.
I am a beginner to Programming in Java and I cannot figure out how to solve this problem:
"Create an Investment application that calculates how many years it will take for a $2,500 investment to be worth at least $5,000 if compounded annually at 7.5%"
I have tried using a for loop and a do-while loop to try solving the problem but it doesn't work. Please Help!
This is what I have after trying everything so far:
/*Investment.java
*This program determines how many years it would take for $2500 to turn into $5000 if
*compounded at 7.5% annually.
*Date: October 27th, 2012
*/
/**
* The following application calculates how many years it will take for $2500 to
* turn into $5000 if compounded at 7.5% annually.
*/
public class Investment {
public static void main(String[] args) {
final int MAX_AMOUNT = 5000;
int investment = 2500;
double interest = 0.075;
double totalValue;
do {
totalValue = (investment + (investment * interest));
} while (totalValue < MAX_AMOUNT);
System.out.println(totalValue);
}
}
Help would be greatly appreciated!
Thanks,
The problem here is that you're just computing the value investment + investment*interest over and over again, and storing it in totalValue. Instead, you need to be accumulating. It could look like:
totalValue = investment;
do {
totalValue = (totalValue + totalValue*interest);
}
while (totalValue < MAX_VALUE);
This way, you keep actually adding the interest and accumulating it.
Additionally, as was commented, you're looking for the number of times that the loop looped, rather than just the value at the end. So you need to count the number of times that the loop is repeated by incrementing a counter each time.
You can do this in a single line, using basic math.
the time (n) to have a value (V) in the futue if initial amount (A) at interest rate (i) compuonded c times per year : n = [ln(V) - ln(A)] / [ ln(c+i) - ln(c)]
double getYearsToMature(double v, double i, int c, double a)
{
return (Math.log(v) - Math.log(a))/(Math.log(c+i) - Math.log(c));
}
since it says in the problem "at least $5000" just round it up and cast to int..
int answer = (Integer) Math.round(getYearsToMature(...));
also you will get some compiler warnings about loss of precision for casting from long to Integer - use float instead of double, or ignore warnings if your numbers are small
You may be able to solve this in a simpler manner by searching for appropriate formulas for calculating this (instead of using a loop). While programming, it's not only important to understand and use language constructs (like loops and conditions) properly, but also to learn the best "algorithm" to do it in an optimal way.
From http://www.csgnetwork.com/directcalccompinttrainer.html (one of the links found through a search):
The time period (n) to have FV in the future if the initial investment A at i interest compounded c times per year:
ln(FV) - ln(A)
n = ------------------
ln(c + i) - ln(c)
NOTE: ln is the natural logarithm function.
For annually compounded interest, the formula becomes:
ln(FV) - ln(A)
n = ------------------
ln(1 + i) - ln(1)
Here's the code using this formula (it'll give you the exact number of years, including a fraction, which you can adjust/truncate and print):
import java.lang.Math;
public class Investment {
public static void main(String[] args) {
final int MAX_AMOUNT = 5000;
int investment = 2500;
double interest = 0.075;
double years;
years = (log(MAX_AMOUNT) - log(investment)) / (log(1 + interest) - log(1))
System.out.println(years);
}
}
Something like:
double years = 0;
while(interest < totalvalue) {
totalValue = investment*interest;
years++;
}
?
To do it iteratively, note that you need to compute the number of years, not the investment amount. Your loop is not adding to the total value, it's recomputing it as if it were the first year each time through the loop. This would work instead:
public class Investment {
public static void main(String[] args) {
final int MAX_AMOUNT = 5000;
int investment = 2500;
double interest = 0.075;
double totalValue;
int years = 0;
do {
totalValue += totalValue * interest;
years++;
} while (totalValue < MAX_AMOUNT);
System.out.println(years);
}
}
However, a better approach is to look at the formula for total value after N years at I percent per annum return, compounded annually:
currentValue = initialInvestment * (1 + I)N
Then you can solve for N, plug in 2500 for initialInvestment and 7500 for currentValue. This will generally give you a fractional value for N, which you then need to round up to get to the number of years needed to reach or exceed the target amount. You'll find the Math.log() (or Math.log10()) function useful for this.
This is my homework it is due Monday the 16th.
I finally got the months to display right but the amounts are wrong.
Also, not necessary but it would be nice to stop and Print something between each loan.
Like loan 1, loan 2, loan 3...
Any help will be appreciated
/*Write the program in Java (without a graphical user interface)
and have it calculate the payment amount for 3 mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5%
- 30 year at 5.75%
Use an array for the different loans.
Display the mortgage payment amount for each loan
and then list the loan balance and interest paid for
each payment over the term of the loan.
Use loops to prevent lists from scrolling off the screen.*/
I have the months correct but the loan amounts are wrong.
import java.io.IOException; //Code that delays ending the program
class MonthlyRhondav4
{
public static void main ( String[] args) throws IOException{
double loanAmount = 200000.00; // $ amount borrowed
double monthlyPayment = 0; // monthly payment for calculating
double loanBalance;
double interestPaid;
double principalPaid;
int paymentCounter;
int lineCounter = 0;
java.text.DecimalFormat dcm = new java.text.DecimalFormat("$,###.00");
int termArray[] = {84, 180, 360}; // Different loan terms in months
double interestArray[] = {0.0535, 0.055, 0.0575};// Different interest rates for the loan
int k =0;// gonna be paymentIndex
/*Code to start the payment list*/
System.out.print("\n\nPlease Press Enter to Continue to the 3 Different Amortization Lists");
System.out.println ();
System.out.println ();
System.in.read();
System.in.read();
/*Display columns*/
System.out.println("Month \t Loan Amount Left\tInterest\t\tPrincipal \n"); //Prints headers for columns
System.out.println ();
/*Loop to calculate and print monthly payments*/
//for(k=0; k<3; k++){// k is going to be paymentIndex to loop through index
for (k = 0; k < interestArray.length; k++) {
for(paymentCounter =1; paymentCounter <= termArray[k]; paymentCounter++) // months through array
{
/********TROUBLE HERE***************************************************************************************/
monthlyPayment = ((loanAmount * (interestArray[k]) * termArray[k]) + loanAmount) / (termArray[k] * 12);
interestPaid = loanAmount*(interestArray[k]/12); //interest paid through array
principalPaid = monthlyPayment-loanAmount*(interestArray[k]/12); //principal paid
/*need to fig monthly payment+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
System.out.println(paymentCounter + "\t" + dcm.format(loanAmount) + "\t\t" + dcm.format(interestPaid) + "\t\t\t" + dcm.format(principalPaid));
lineCounter++; //Increment the display counter
if (lineCounter > 11 && paymentCounter < termArray[k]*12) //Check to see if 12
{
System.out.println ("Please Press Enter to Continue the List" ); //Code to delay ending the program
System.in.read();
System.in.read();
lineCounter = 0;
}
}
loanAmount = (loanAmount - (monthlyPayment-loanAmount*(interestArray[k]/12))); //Calculate new loan amount
}
}//ends public static void main
}//ends public class
One observation -- you're not doing anything with the loan balance. The reason why nothing is changing is that having computed the interest and principal amounts of a given payment, you're not reducing the loan balance by the principal portion of the payment. You need to change your code to display the current loan balance and to compute the principal/interest split from the current loan balance and not the original loan amount.
Edited
Ok -- I see you were trying to update the balance, but you have it outside the loop for the loan. That needs to be inside the loop so that it is updated for each payment. Also, you have things like loanAmount * (interestArray[k] / 12) over and over again. Consider using variables, such as
double interestPaid = loanAmount * (interestArray[k] / 12)
This will make your code easier to read and more maintainable since if you find a mistake in the calculation, you only have to fix the mistake in one place rather than having to fix it everywhere you had the calculation.
I also don't see where you're calculating the monthly payment. That's a function of the original loan amount, number of payments, and interest rate. Remember, the monthly payment is fixed and the interest/principal split of each payment will change as the loan is paid down. You might find http://en.wikipedia.org/wiki/Mortgage_calculator useful to figure out the formula for the monthly payment.
first : never ever use double to calculate something... That's an advice you have to remember. If you don't want to trust me, please search Google for "java double computation" or something like that, and you'll see. Or read the excellent book "Effective Java"
BigDecimal class is there to have correct numbers in Java
A lot of mistakes. For instance you never set the monthlyPayment to anything but 0. You also do not use loanBalance. loanAmount should be a constant. You can also simplify redundant calculations. Example:
interestPaid = loanBalance*(interestArray[k]/12);
principalPaid = monthlyPayment-interestPaid;
instead of
interestPaid = loanBalance*(interestArray[k]/12);
principalPaid = monthlyPayment-loanBalance*(interestArray[k]/12);
I am also not sure you have the correct interest rate formulas, but am not going to check until you remove some of the more obvious errors.