I am trying to create a program that calculates the futureValue that is in the following formula
futureValue = investmentAmount × (1 + monthlyInterestRate)^years×12
It is a visual program and it calculates the futureValue.Variables: investmentAmount monthlyInterestRate and years are taken from textfields.Here my code is like this
public void Calculator(){
double x = (Double.parseDouble(AnnualInterestRate.getText())/12) + 1;
double y = Double.parseDouble(Years.getText()) * 12;
double mult = Math.pow(x, y);
double futureValue = Double.parseDouble(InvesmentAmount.getText()) * mult;
lblNewLabel_3.setText("$" + String.format("%.2f",futureValue));
}
for these values:
InvesmentAmount : 1000
Years : 2
AnnualInterestRate : 6.5
futureValue should be 1,138.43 but futureValue that is calculated by my program is 32491635,80
I can't see the mistake and It would be great if anybody could help.
If your user is supposed to be inputting the interest rate as a percentage, you need to divide it by 100 as part of your calculation. E.g.
double x = (Double.parseDouble(AnnualInterestRate.getText())/1200) + 1;
Output: $1138.43
Related
This are other problems I ran into that is having the same issue. Can anyone point out my logic error in the following below:
Question: A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree... (Exercise 4.5)
This was my response:
import java.util.Scanner;
public class Exercise04_05 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of sides: ");
double n = input.nextDouble();
System.out.print("Enter the side: ");
double s = input.nextDouble();
double area = n * Math.pow(s, 2) / 4 * Math.tan(Math.PI / n );
System.out.println("The area of the polygon is " + area);
}
}
Please explain where the Logic error is. i commented out the code or else I'll keep getting errors preventing me from submitting the question.
Your formula is wrong and it contains an error.
First / 4 is an integer division which is rounded to an int, so you get mostly an error. You have to use / 4.0 so you get the right division.
The formula for calculation the area of a polygon is
A = 1 / 4 * n * s2 * cot(PI / n)
Note it is cotangens, not tangens. As java.math has no cotangens you have to calculate it by yourself, e.g. 1 / Math.tan(x).
So finally this should work for you:
double area = n / 4.0 * Math.pow(s, 2) / Math.tan(Math.PI / n );
Here is my code. For some reason my BMI is not calculated correctly.
When I check the output on a calculator for this : (10/((10/100)^2))) I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:
import javax.swing.*;
public class BMI {
public static void main(String args[]) {
int height;
int weight;
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
weight = Integer.parseInt(getweight);
height = Integer.parseInt(getheight);
double bmi;
bmi = (weight/((height/100)^2));
JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
}
}
^ in java does not mean to raise to a power. It means XOR.
You can use java's Math.pow()
And you might want to consider using double instead of int—that is:
double height;
double weight;
Note that 199/100 evaluates to 1.
we can use
Math.pow(2, 4);
this mean 2 to the power 4 (2^4)
answer = 16
^ is not the operator you want. You are looking for the pow method of java.lang.Math.
You can use Math.pow(value, power).
Example:
Math.pow(23, 5); // 23 to the fifth power
Your calculation is likely the culprit. Try using:
bmi = weight / Math.pow(height / 100.0, 2.0);
Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.
Too late for the OP of course, but still...
Rearranging the expression as:
int bmi = (10000 * weight) / (height * height)
Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:
double bmi = (10000.0 * weight) / (height * height)
would still be an improvement.
You should use below method-
Math.pow(double a, double b)
From (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-)
Returns the value of the first argument raised to the power of the second argument.
int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);
1) We usually do not use int data types to height, weight, distance,
temperature etc.(variables which can have decimal points)
Therefore height, weight should be double or float.
but double is more accurate than float when you have more decimal points
2) And instead of ^, you can change that calculation as below using Math.pow()
bmi = (weight/(Math.pow(height/100, 2)));
3) Math.pow() method has below definition
Math.pow(double var_1, double var_2);
Example:
i) Math.pow(8, 2) is produced 64 (8 to the power 2)
ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)
I did the benchmarking with Math.pow(x,2) and x*x,
the result is that Math.pow() is easily forty times slower than manually multiplying it by itself, so i don't recommend it for anything where a little bit of performance is required.
Here's the results:
proof_of_work: 19.284756867003345
time for Math.pow(x,2) in ns: 35143
proof_of_work: 19.284756867003345
time for x*x in ns: 884
manual calculation is 39 times faster
and here's the test-code
double r1 = 4.391441320;
long multiply_d1 = System.nanoTime();
double multiply_dr = Math.pow(r1,2);
long multiply_d2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_dr));
System.out.println(("time for Math.pow(x,2) in ns: ") + (multiply_d2 - multiply_d1));
long multiply_t1 = System.nanoTime();
double multiply_tr = r1*r1;
long multiply_t2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_tr));
System.out.println(("time for x*x in ns: ") + (multiply_t2 - multiply_t1));
System.out.println(("manual calculation is ") + ((multiply_d2 - multiply_d1) / (multiply_t2 - multiply_t1)) + (" times faster"));
Most efficient solution is
public Float fastPow(Float number, Integer power) {
if (power == 0) {
return 1.0f;
} else if (power % 2 == 1) {
return fastPow(number, power - 1) * number;
} else {
return fastPow(number * number, power / 2);
}
}
Let A is our number and N our power. Then A^2^N = (A^2)^N. And A^N = (A^2)^N/2. The function above reflects this relationship.
I'm making a program for my java class that calculates the population for a year given the start year (2011) and increases the population by 1.2% every year. The population for 2011 is 7.000 (I'm using decimals, instead of billions). I currently have this code.
int startYear = 2011;
int endYear = user_input.nextInt();
double t = 1.2; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
DecimalFormat nf = new DecimalFormat("2");
System.out.println("Population in " + endYear + ": " (nf.format(pEnd)));
There's no errors in the code, everything works, but I'm having troubles with the pEnd equation. Currently when I enter 2016 for the end year, i get 22824. I've tried googling a formula, but i can't find anything. Do any of you guys have an idea of the formula? If you enter 2016 for the end year, it should be around 7.433
You're incrementing by a factor of 1.2, which would represent 120% instead of 1.2%. I think what you want is :
double t = 0.012;
This change gives me an exact value of 7.4328558258175175 from 2011 to 2016.
EDIT : here's the code as requested by the author :
public static void main(String args[]){
int startYear = 2011;
int endYear = 2016;
double t = 0.012; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
System.out.println("Population in " + endYear + ": " + pEnd);
}
Use Math.pow(1 + t / 100, nbr) instead of Math.exp(nbr * t) because you need (1+t/100)^nbr (i.e. multiply 1 + t / 100 on itself nbr times), not exp^(nbr*t):
double pEnd = pStart * Math.pow(1 + t / 100, nbr); // Ending population of user input
Try this.
double pEnd = pStart * Math.pow(1.0 + t / 100, nbr);
The formula to compute the monthly payment is as follows:
monthlyPayment = (loanAmount x monthlyInterestRate) / (1 – (1 / (1 + monthlyInterestRate)numberOfYears x 12 ))
In the above formula, you have to compute (1 + monthlyInterestRate)numberOfYears x 12 ). The pow(a,b) method in the Java API Math class can be used to compute ab.
so how to put this in pow(a,b) method ?
The javadoc for the java.lang.Math class might help you here. Is there something specific you don't understand about that?
So the code to compute the b power of a should look something like this:
double result = Math.pow(a, b);
The formula you have does not look quite right. From Exact_formula_for_monthly_payment The formula should be
P= (L i)/(1- 1/(1+i)^n )
Where L is the loan amount, i is the monthly interest, and n number of periods. In your formula
monthlyPayment = (loanAmount x monthlyInterestRate) / (1 – (1 / (1 + monthlyInterestRate)numberOfYears x 12 ))
the exponential sign has been missed out. I think you want
monthlyPayment = (loanAmount x monthlyInterestRate) / (1 – (1 / (1 + monthlyInterestRate) ^ (numberOfYears x 12) ))
To calculate this in java you would want
monthlyPayment = (loanAmount * monthlyInterestRate) /
(1 – (1 / Math.pow(1 + monthlyInterestRate,numberOfYears * 12)));
Which could be simplified to
monthlyPayment = (loanAmount * monthlyInterestRate) /
(1 – Math.pow(1 + monthlyInterestRate,-numberOfYears * 12));
using a negative exponent.
I am supposed to make a monthly payment calculator in java with the given formula.
The formula for me to use is
M = P * i/ 1 - (1+i)^-n
where
P is the loan principal (i.e. the amount borrowed)
i is monthly interest rate (annual_interest_rate / 12; expressed as decimal)
N is time (number of monthly payments in total years of loan; i.e. years * 12)
The code below is my attempted function to get the monthly payment.
But if I put in 6 years with a loan amount of 200, I get 140 using the formula.
I am stumped as to why I get that number. Any help would be appreciated
public static int calMonthlyPay(double loanAmt, int y) {
double m = 0.0, interest = 0.0, annualIRate = 0.0;
double months = 0.0;
months = y * 12;
annualIRate = getAnnualIRate(y);
interest = annualIRate / 12;
System.out.println(interest);
System.out.println(months);
System.out.println(loanAmt);
System.out.println(y);
m = (loanAmt * (interest - Math.pow((1 + interest), -months))); // This is my formula calculation
System.out.println(m);
return 0;
}
private static double getAnnualIRate(int y) {
switch (y) {
case 2:
return 5.7;
case 3:
return 6.2;
case 4:
return 6.8;
case 5:
return 7.5;
case 6:
return 8.4;
default:
return 8.4;
}
}
If I understood your formula right, it should be:
m = loanAmt * interest - Math.pow(1 + interest, -months);
What you have now is :
m = (loanAmt * (interest / 1 - Math.pow((1 + interest), -months))) =
(loanAmt * (interest - Math.pow((1 + interest), -months)))
You should use the parentheses correctly :
m = loanAmt * (interest / (1 - Math.pow(1 + interest, -months)));
Your formula is incorrect, it need to be
loanAmt * (interest / (1 - Math.pow (1 + interest, -months)));
And there's a error in interest value formula, it need to be
interest = annualIRate / 100 / 12;
So your method calMonthlyPay(200, 6) gives 3 now, which is correct.