Method not dividing for desired double value - java

In my program, I'm trying to divide two double values and return the quotient of it. Like this:
public double getMonthlyPayment(){
double monthlyRate = AnnualInterestRate / 1200;
double numberOfMonths = numberOfYears * 12;
double dividend = (loanAmount * monthlyRate);
double divisor = (1 - Math.pow(1+monthlyRate, -numberOfMonths));
return dividend / divisor;
}
Currently it's not returning the value I'm expecting. It's only returning the dividend value and not the value when dividend is divided by divisor.
For example, since this is a loan calculator, I need a loan of $2000 with 5% interest for 2 years. In order to achieve this value, you would need to use a certain equation.
I've made my own form of that equation in the code above and it's only returning the dividend value, which is (loanAmount * monthlyRate), instead of returning dividend value divided by (1 - Math.pow(1+monthlyRate, -numberOfMonths))
Could someone help me with this?
Thanks in advance for any help.

Your code doesn't show, but if AnnualInterestRate is an int, then the division by 1200 is done using integer logic, and the result (an integer) is then coerced to double. Specifying 1200.0 will force coercion of AnnualInterestRate to double before the division.

We do not know data types of all variables in your question. If the data type of right side is integer and left side is double, explicitly cast the result to double
Correct code should be:
public double getMonthlyPayment(){
double monthlyRate = (double)AnnualInterestRate / 1200;
double numberOfMonths = (double) numberOfYears * 12;
double dividend = (loanAmount * monthlyRate);// Assuming loanAmount is double
double divisor = (1 - Math.pow(1+monthlyRate, -numberOfMonths));
return dividend / divisor;
}

Related

Why don't I get any decimal place when dividing by e.g. 1000000000 [duplicate]

For this code block:
int num = 5;
int denom = 7;
double d = num / denom;
the value of d is 0.0. It can be forced to work by casting:
double d = ((double) num) / denom;
But is there another way to get the correct double result? I don't like casting primitives, who knows what may happen.
double num = 5;
That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:
Widening primitive conversions do not
lose information about the overall
magnitude of a numeric value.
[...]
Conversion of an int or a long value
to float, or of a long value to
double, may result in loss of
precision-that is, the result may lose
some of the least significant bits of
the value. In this case, the resulting
floating-point value will be a
correctly rounded version of the
integer value, using IEEE 754
round-to-nearest mode (§4.2.4).
5 can be expressed exactly as a double.
What's wrong with casting primitives?
If you don't want to cast for some reason, you could do
double d = num * 1.0 / denom;
I don't like casting primitives, who knows what may happen.
Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.
You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:
double d = num / (double) denom;
If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.
double d = 5 / (double) 20; //cast to double, to do floating point calculations
Note that casting the result won't do it
double d = (double)(5 / 20); //produces 0.0
Type Casting Is The Only Way
May be you will not do it explicitly but it will happen.
Now, there are several ways we can try to get precise double value (where num and denom are int type, and of-course with casting)-
with explicit casting:
double d = (double) num / denom;
double d = ((double) num) / denom;
double d = num / (double) denom;
double d = (double) num / (double) denom;
but not double d = (double) (num / denom);
with implicit casting:
double d = num * 1.0 / denom;
double d = num / 1d / denom;
double d = ( num + 0.0 ) / denom;
double d = num; d /= denom;
but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );
Now if you are asking- Which one is better? explicit? or implicit?
Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.
Also, an extra operation will definitely not make your code more efficient. Right?
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;
Note that casting the result won't do it. Because first division is done as per precedence rule.
double d = (double)(5 / 20); //produces 0.0
I do not think there is any problem with casting as such you are thinking about.
use something like:
double step = 1d / 5;
(1d is a cast to double)
Best way to do this is
int i = 3;
Double d = i * 1.0;
d is 3.0 now.
You might consider wrapping the operations. For example:
class Utils
{
public static double divide(int num, int denom) {
return ((double) num) / denom;
}
}
This allows you to look up (just once) whether the cast does exactly what you want. This method could also be subject to tests, to ensure that it continues to do what you want. It also doesn't matter what trick you use to cause the division (you could use any of the answers here), as long as it results in the correct result. Anywhere you need to divide two integers, you can now just call Utils::divide and trust that it does the right thing.
just use this.
int fxd=1;
double percent= (double)(fxd*40)/100;
Just add "D".
int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D

How to prevent double from rounding up to two decimal

I'm trying to calculate a percentage(9% tax) of a item
double amount = 55.4;
double total = amount * 0.09;
System.out.printf ("%f \n", total);
System.out.printf ("%.2f \n", total);
Returns
4.986000
4.99
How do I make it return 4.98?
Thanks!
Use BigDecimal instead of double.
double is floating point, which cannot accurately represent all fractional amounts, hence the "rounding" problem that you are.experiencing.
BigDecimal is arbitrary-precision, and so doesn't have that problem.
If you want to chop off the thousands place multiple your total by 100 and cast it to an int, then divide it by 100 and cast it to a double:
double amount = 55.4;
double total = amount * 0.09;
int truncated = (int) (total * 100);
double val = truncated * .01;
System.out.printf("%.2f\n", val);
This will give you:
4.98
This can also be done with
double val = Math.floor(total * 100) / 100;
System.out.printf("%.2f\n", val);

How to calculate the percentage in java? [duplicate]

For this code block:
int num = 5;
int denom = 7;
double d = num / denom;
the value of d is 0.0. It can be forced to work by casting:
double d = ((double) num) / denom;
But is there another way to get the correct double result? I don't like casting primitives, who knows what may happen.
double num = 5;
That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:
Widening primitive conversions do not
lose information about the overall
magnitude of a numeric value.
[...]
Conversion of an int or a long value
to float, or of a long value to
double, may result in loss of
precision-that is, the result may lose
some of the least significant bits of
the value. In this case, the resulting
floating-point value will be a
correctly rounded version of the
integer value, using IEEE 754
round-to-nearest mode (§4.2.4).
5 can be expressed exactly as a double.
What's wrong with casting primitives?
If you don't want to cast for some reason, you could do
double d = num * 1.0 / denom;
I don't like casting primitives, who knows what may happen.
Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.
You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:
double d = num / (double) denom;
If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.
double d = 5 / (double) 20; //cast to double, to do floating point calculations
Note that casting the result won't do it
double d = (double)(5 / 20); //produces 0.0
Type Casting Is The Only Way
May be you will not do it explicitly but it will happen.
Now, there are several ways we can try to get precise double value (where num and denom are int type, and of-course with casting)-
with explicit casting:
double d = (double) num / denom;
double d = ((double) num) / denom;
double d = num / (double) denom;
double d = (double) num / (double) denom;
but not double d = (double) (num / denom);
with implicit casting:
double d = num * 1.0 / denom;
double d = num / 1d / denom;
double d = ( num + 0.0 ) / denom;
double d = num; d /= denom;
but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );
Now if you are asking- Which one is better? explicit? or implicit?
Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.
Also, an extra operation will definitely not make your code more efficient. Right?
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;
Note that casting the result won't do it. Because first division is done as per precedence rule.
double d = (double)(5 / 20); //produces 0.0
I do not think there is any problem with casting as such you are thinking about.
use something like:
double step = 1d / 5;
(1d is a cast to double)
Best way to do this is
int i = 3;
Double d = i * 1.0;
d is 3.0 now.
You might consider wrapping the operations. For example:
class Utils
{
public static double divide(int num, int denom) {
return ((double) num) / denom;
}
}
This allows you to look up (just once) whether the cast does exactly what you want. This method could also be subject to tests, to ensure that it continues to do what you want. It also doesn't matter what trick you use to cause the division (you could use any of the answers here), as long as it results in the correct result. Anywhere you need to divide two integers, you can now just call Utils::divide and trust that it does the right thing.
just use this.
int fxd=1;
double percent= (double)(fxd*40)/100;
Just add "D".
int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D

Raising a number to a power in Java

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.

Integer division: How do you produce a double?

For this code block:
int num = 5;
int denom = 7;
double d = num / denom;
the value of d is 0.0. It can be forced to work by casting:
double d = ((double) num) / denom;
But is there another way to get the correct double result? I don't like casting primitives, who knows what may happen.
double num = 5;
That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:
Widening primitive conversions do not
lose information about the overall
magnitude of a numeric value.
[...]
Conversion of an int or a long value
to float, or of a long value to
double, may result in loss of
precision-that is, the result may lose
some of the least significant bits of
the value. In this case, the resulting
floating-point value will be a
correctly rounded version of the
integer value, using IEEE 754
round-to-nearest mode (§4.2.4).
5 can be expressed exactly as a double.
What's wrong with casting primitives?
If you don't want to cast for some reason, you could do
double d = num * 1.0 / denom;
I don't like casting primitives, who knows what may happen.
Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.
You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:
double d = num / (double) denom;
If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.
double d = 5 / (double) 20; //cast to double, to do floating point calculations
Note that casting the result won't do it
double d = (double)(5 / 20); //produces 0.0
Type Casting Is The Only Way
May be you will not do it explicitly but it will happen.
Now, there are several ways we can try to get precise double value (where num and denom are int type, and of-course with casting)-
with explicit casting:
double d = (double) num / denom;
double d = ((double) num) / denom;
double d = num / (double) denom;
double d = (double) num / (double) denom;
but not double d = (double) (num / denom);
with implicit casting:
double d = num * 1.0 / denom;
double d = num / 1d / denom;
double d = ( num + 0.0 ) / denom;
double d = num; d /= denom;
but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );
Now if you are asking- Which one is better? explicit? or implicit?
Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.
Also, an extra operation will definitely not make your code more efficient. Right?
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;
Note that casting the result won't do it. Because first division is done as per precedence rule.
double d = (double)(5 / 20); //produces 0.0
I do not think there is any problem with casting as such you are thinking about.
use something like:
double step = 1d / 5;
(1d is a cast to double)
Best way to do this is
int i = 3;
Double d = i * 1.0;
d is 3.0 now.
You might consider wrapping the operations. For example:
class Utils
{
public static double divide(int num, int denom) {
return ((double) num) / denom;
}
}
This allows you to look up (just once) whether the cast does exactly what you want. This method could also be subject to tests, to ensure that it continues to do what you want. It also doesn't matter what trick you use to cause the division (you could use any of the answers here), as long as it results in the correct result. Anywhere you need to divide two integers, you can now just call Utils::divide and trust that it does the right thing.
just use this.
int fxd=1;
double percent= (double)(fxd*40)/100;
Just add "D".
int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D

Categories