Cannot figure out how to raise the formula to a power. I have imported the java.lang.Math in java also. I just keep getting the Sytax error on "Math" delete this token and cannot invoke pow(double) on the primitive data type double errors
This is the formula assuming a 30 year loan
Annuity Factor = (0.003125*(1+0.003125)^360)/(((1+0.003125)^360)-1)
the 360 is 30 years time 12 months to get the monthly payment
import java.util.Scanner;
import java.lang.Math;
public class HW3Method {
public static void main(String[] args) {
// main method for user inputs
Scanner info = new Scanner(System.in);
System.out.println("Enter the starting annual rate as a percent (n.nnn)");
double startRate = info.nextDouble();
System.out.println("Enter the ending annual rate as a percent (n.nnn)");
double endRate = info.nextDouble();
System.out.println("Enter the annual intrest rate increments as a percent (n.nnn)");
double rateIncrease = info.nextDouble();
System.out.println("Enter the first term in years for calculating payments");
double firstTerm = info.nextDouble();
System.out.println("Enter the last term in years for calculating payments");
double lastTerm = info.nextDouble();
System.out.println("Enter the term increment in years");
int termIncrement = info.nextInt();
System.out.println("Enter the loan amount");
double loanAmount = info.nextDouble();
double mtp = firstTerm * 12;
}
public double calcAnnuity(double mtp ) {
double annuityFactor = (0.003125*(1+0.003125)Math.pow(mtp));
return annuityFactor;
}
}
Explanation
You are using the method Math.pow wrong. It wants two arguments, the base and the exponent. You wrote:
0.003125 * (1 + 0.003125) Math.pow(mtp)
But you need to write:
0.003125 * Math.pow(1.0 + 0.003125, mtp)
Notes
Note that 1.0 + 0.003125 can be simplified to just 1.003125, so:
0.003125 * Math.pow(1.003125, mtp)
Even better would be to store that magical number somewhere as constant, then you only need to change one variable and not many:
private static final int FACTOR = 0.003125;
And then use that constant:
FACTOR * Math.pow(1.0 + FACTOR, mtp)
Documentation
From the official documentation of Math.pow:
public static double pow(double a, double b)
Returns the value of the first argument raised to the power of the second argument. Special cases: [...]
Related
I've tried with the following inputs:
principal= 1000, rate=4, timesapplied=2(half-yearly), elapsedyears=2
import javax.swing.*;
import java.math.BigDecimal;
public class CICalc {
public static void main(String[] args) {
Double principal;
Double rate;
Double timesapplied;
Double elapsedyears;
principal= Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
rate=Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
timesapplied=Double.parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
elapsedyears=Double.parseDouble(JOptionPane.showInputDialog("Enter the amount of time(In years and if in months, write them in this format- month/12) the principal is being invested for"));
BigDecimal CI;
BigDecimal inf;
inf= BigDecimal.valueOf(Math.pow(rate+(1/timesapplied*100),elapsedyears*timesapplied));
CI= (BigDecimal.valueOf(principal)).multiply(inf);
BigDecimal P= CI.subtract(BigDecimal.valueOf(principal));
JOptionPane.showMessageDialog(null,"The Compound Interest for "+elapsedyears+" years is "+CI+"$ and the the interest gained is "+P+"$");
}
}
Can someone please point out the mistakes and help me out? Actually, I had made this using only Double but the problem was that the result had way too many decimal points. So I had to use BigDecimal.
Actually, I had made this using only Double but the problem was that
the result had way too many decimal points. So I had to use
BigDecimal.
Use BigDecimal setScale(int newScale, RoundingMode roundingMode) to round the result up to the required number of decimal places.
import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.swing.JOptionPane;
class Main {
public static void main(String[] args) {
double principal = Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
double rate = Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
double timesapplied = Double
.parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
double elapsedyears = Double.parseDouble(JOptionPane.showInputDialog("Enter the number of years"));
double base = 1.0 + rate / (timesapplied * 100.0);
double exponent = elapsedyears * timesapplied;
double inf = Math.pow(base, exponent);
double CI = principal * inf;
double P = CI - principal;
JOptionPane.showMessageDialog(null,
"The Compound Interest for " + BigDecimal.valueOf(elapsedyears).setScale(2, RoundingMode.HALF_UP)
+ " years is " + BigDecimal.valueOf(CI).setScale(2, RoundingMode.HALF_UP)
+ "$ and the the interest gained is " + BigDecimal.valueOf(P).setScale(2, RoundingMode.HALF_UP)
+ "$");
}
}
Your formula for compound interest was wrong. The formula is
final amount = initial amount times
1 + interest rate / number of times interest applied
raised to the power of number of times interest applied
times number of time periods elapsed
The interest rate, which is normally defined as a percentage per year has to be converted to a number per time period by dividing by 100 and dividing by the number of time periods in a year.
As far as your code, I made a method to get the input values.
I also broke up the compound interest calculation so I could verify the results of each part of the calculation.
Here's the revised code.
import java.text.NumberFormat;
import javax.swing.JOptionPane;
public class CICalc {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getCurrencyInstance();
double principal = getValue("Enter the principal amount");
double rate = getValue("Enter the yearly interest rate");
double timesapplied = getValue("Enter the number of times "
+ "the principal is compounded per year");
double elapsedmonths = getValue("Enter the amount of time "
+ "in months the principal is invested");
double temp1 = 1.0d + rate * 0.01d / timesapplied;
double temp2 = timesapplied * elapsedmonths / 12d;
double finalAmount = principal * Math.pow(temp1, temp2);
JOptionPane.showMessageDialog(null,
"The total amount returned after " +
elapsedmonths +
" months is " + nf.format(finalAmount) +
" and the the interest gained is " +
nf.format(finalAmount - principal));
}
private static double getValue(String prompt) {
String response = JOptionPane.showInputDialog(prompt);
return Double.parseDouble(response);
}
}
This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 4 years ago.
import java.util.*;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter price: $");
float price = keyboard.nextFloat();
System.out.println("Early payment (Y/N): ");
String char1 = keyboard.nextLine();
float amount = price;
if (char1.equals('Y'))
{
amount = price * 0.9;
}
System.out.printf("Amount due: $%0.2f\n", amount);
}
}
when compiling it gives the error of possible lossy conversion, regardless if i pass an int or float.. what is the issue here?
In Java by default every decimal number is considered double. You are multiplying a float by double which result in a double:
float price = 10.7f;
float result = price * 0.9; //this does not work
Here, we have two options. The first one is to convert 0.9 as float, putting the f in the front of the number:
float result = price * 0.9f;
The second option is to hold the result as double:
double result = price * 0.9;
Please, use double/float only for doing simple tests. Here we have a good explanation about the difference between Double and BigDecimal:
The main issue is that 0.9 is a double, which causes the value of price * 0.9 to be coerced to a double as well. To prevent that, you should use 0.9f to indicate you want a float type.
You also have an issue with char1 actually being a String, not a char, so char1.equals('Y') will always be false.
In addition, your %0.2f format says you want to zero-fill your output, but you neglected to specify a minimum width. Something like %04.2f should work.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter price: $");
float price = keyboard.nextFloat();
System.out.println("Early payment (Y/N): ");
String str1 = keyboard.next();
float amount = price;
if (str1.equals("Y")) {
amount = price * 0.9f;
}
System.out.printf("Amount due: $%04.2f\n", amount);
}
}
package methods;
import java.util.Scanner;
/**
*
* #author Billy
*/
public class Methods {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double Loanamount; // Loan amount from user
double Aintrate; // User's annual interest rate
double months; // Number of months on loan
double monp; // Monthly payment
double Mintrate; // Monthly interest rate
double n; // The number of payments
// declare an instance of Scanner to read the datastream from the keyboard.
Scanner kb = new Scanner(System.in);
// Get user's loan amount
System.out.print("Please enter your total loan amount: ");
Loanamount = kb.nextDouble();
// Get user's interest rate
System.out.print("Please enter your annual interest rate as a decimal: ");
Aintrate = kb.nextDouble();
// Get user's number of months
System.out.print("Please enter the number of months left on your loan: ");
months = kb.nextDouble();
// Calculate montly interest rate
Mintrate = ((Aintrate / 12));
System.out.println("Your monthly interest rate is " + " " + Mintrate);
// Calculate number of payments
n = ((months * 12));
// Calculate monthly payment
My next job is to find out the monthly payment using this formula.
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Where
M = monthly mortgage payment
P = The amount borrowed (Loanamount)
i = Monthly interest rate (Mintrate)
n = the number of payments
I tried the following but I just cant figure it out
monp = Loanamount [Mintrate(1+ Mintrate)^n] / [(1+ Mintrate)^n-1 ];
You need to use Math.pow effectivley here.
Try using following in your code
monp = Loanamount*(Mintrate*Math.pow((1+ Mintrate),n)) / (Math.pow((1+ Mintrate),n-1 ) ;
Math.pow is what you need instead of ^. Also you can't use [ or ]. You have to use parenthesis ( and ).
More math functions can be found at:
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
The method for ^ is called Math.pow(double a, double b); in Java.
Where a is the number to be raised b times.
Your formula would then look like monp = Loanamount Math.pow((Mintrate(1+ Mintrate), n)) / (Math.pow((1+ Mintrate), n-1));
Reference
You need to call Math.pow(double,double)
OR you could import the required class as..
import static java.lang.Math.pow;
and then use pow() function
I am just practicing Java as a beginner. So here is the question:
Suppose you save $100 each month into a savings account with the annual interest rate 5%. Thus, the monthly interest rate is 0.00417. After the first month, the value in the account becomes 100 * (1 + 0.00417) = 100.417 and the second month will be (100 + firstMonthValue) * 1.00417, and then goes on like so every month. So here is my code:
import javax.swing.JOptionPane;
public class vinalcialApplication {
public static void main(String args[]){
String monthlySaving = JOptionPane.showInputDialog("Enter the monthly savings");
double monthsaving = Double.parseDouble(monthlySaving);
//define monthly rate
double monthlyrate = 1.00417;
double totalrate = monthlyrate + 0.00417;
double firstMonthValue = monthsaving * (totalrate);
double secondMonthValue = (firstMonthValue + 100)*(monthlyrate);
double thridMonthValue = (secondMonthValue + 100) * (monthlyrate);
.........
System.out.print("After the sixth month, the account value is " sixthMonthValue);
}
}
I mean the code works but it is too much code to write.. I am sure I can use a loop or if statement to do this but haven't figured a way to do it yet.. can you please help?
Thank you.
If I understand correctly, this is called compound interest.
There is a mathematical formula to achieve what you wanted without looping.
Here is the formula from wikipedia
Where,
A = future value, P = principal amount (initial investment),r = annual nominal interest, rate, n = number of times the interest is compounded per year,t = number of years
Hope this helps you in solving what you wanted. I can give you sample code, but I think it is fairly easy to convert this formula to java statement. Let us know if you need any more info.
Source: http://en.wikipedia.org/wiki/Compound_interest
import javax.swing.JOptionPane;
public class vinalcialApplication {
public static void main(String args[]){
String monthlySaving = JOptionPane.showInputDialog("Enter the monthly savings");
double monthsaving = Double.parseDouble(monthlySaving);
//define monthly rate
double monthlyrate = 1.00417;
double totalrate = monthlyrate + 0.00417;
double value = monthsaving * (totalrate);
for(int i = 1; i<6;i++) {
value = (value + 100)*(monthlyrate);
}
System.out.print("After the sixth month, the account value is " value);
}
The maths is probably wrong, but the basic concept is sound.
public static void main(String[] args) {
double monthsaving = 100;
double monthlyrate = 1.00417;
double savings = 0;
// Loop for six months...
for (int index = 0; index < 6; index++) {
savings += monthsaving * monthlyrate;
System.out.println(index + ":" + savings);
}
System.out.println(savings);
}
Take a closer look at Control Flow Statements, paying attaching with while, do-while and for statements
I wrote a simple program that receives several inputs and it does a future investment calculation.
However, for some reason, when I enter the following values:
investment = 1
interest = 5
year = 1
I get Your future value is 65.34496113081846 when it should be 1.05.
import java.util.*;
public class futurevalue
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("This program will calculate your future investment value");
System.out.println("Enter investment amount: ");
double investment = sc.nextDouble();
System.out.println("Enter annual interest amount: ");
double interest = sc.nextDouble();
System.out.println("Enter number of years: ");
int year = sc.nextInt();
double futureValue = investment * (Math.pow(1 + interest, year*12));
System.out.println("Your future value is " + futureValue);
}
}
Found my mistake. I divided my interest twice.
You should divide your interest by 100.
How is the interest rate being entered? Should you not divide it by 100 before adding 1 inside Math.pow?
Example: Monthly interest = 1%, if you enter 1, your Math.pow would be Math.pow(1+1, year*12) which would be incorrect.
Yes, your main error is not dividing by 100 to convert from percents to proportion, but you have another error:
If you have an APR of 5% the formula you need to use to calculate a compounding monthly interest isn't 5%/12, it's
(0.05+1)^(1/12)-1
And then the return for that investment ends up being:
1 * ( (0.05+1)^(1/12)-1 +1 )^(1 * 12) =
1 * ( (0.05+1)^(1/12) )^(12) =
1 * ( 0.05+1 ) = 1.05
exactly.