why the division operator isn't working properly? [duplicate] - java

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

Related

DecimalFormat is not working properly in Java program converting Fahrenheit to Celsius [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 make the int into double inside the text without changing the int one [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

I converted double to int, but there is still an error, explain why?

int x1, x2; double d;
d = (int)(Math.sqrt(b*b - 4*a*c));
if (d >= 0) {
x1 = (-b + d) / 2*a; // on this line
"Type mismatch: cannot convert from double to int"
Here x1 shouldn't be an int. It looks like you're using it to store a root of a quadratic equation, which of course is likely not to be a whole number.
Change x1 (and probably x2 too) to be a double and the problem will go away.
Incidentally, you want parentheses around 2 * a, otherwise you're effectively putting a on the numerator, not the denominator.
d is a double, so (-b + d) is a double. Even if b isn't a double, it'll get widened to one for that expression. Therefore, (-b + d) / 2*a is a double. Java won't let you implicitly convert that double expression to an int, because you could lose precision.
You simply need to do a cast to int at the point where you want to store the result of a double calculation into an int:
public class Test {
public static void main(String[] args) {
double a = 1.0;
double b = 3.0;
double c = 2.0;
int x1, x2;
double d;
d = Math.sqrt(b * b - 4 * a * c);
if (d >= 0) {
x1 = (int) ((-b + d) / 2 * a); // on this line
}
}
}
You should also take another look at where you are doing the sign test d >= 0. It will work, because the result of a Math.sqrt call is either a non-negative number or a NaN, but testing the square root operand before the call would be clearer.
Your error is from:
x1 = (-b + d) / 2*a;
Your variable did still defined as a double. When you add it to -b this will return a double.
Try saving this line as a new int variable instead of d:
Int temp = (int)(Math.sqrt(b*b - 4*a*c));
d is still a double, because it was declared as a double. Casting only changes the type of a value; it won't change d itself to an int. If you want d to be an int, declare it as an int, like this:
int d;
instead of
double d;
and keep the rest of your code the same. This should fix the problem.
If you're deadset on ending up with an int, you can do the following:
double answer = (-b + d) / 2*a;
x1 = new Double(answer).intValue();
Otherwise, the other answers have sufficiently told you why you're running into issues with casting.
How to convert Double to int directly?

About auto rounding result in java from double to integer?

The output of below code in Java is 3.0.
Why isn't it 3.3333333...?
double a = 10 / 3;
System.out.println(a);
Because int / int returns an int (regardless of what you assign it to afterwards).
So 10 / 3 returns 3 (integer division rounds down).
This would only then get converted to double.
To fix this, make one of the values a double (so it's double / int, which returns a double):
double a = 10.0 / 3;
or
double a = (double)10 / 3;

Java why doesn't my calculation work on this code?

Hi I'm trying to run a calculation but I can't seem to put it all on one line, I have to split the result into two seperate lines to achieve the desired result (which seems a bit long winded).
Can anyone explain where I'm going wrong?
both x and y are doubles.
Example 1: (incorrect)
y=0.68
x= (Math.round(y* 10))/10;
result x=0
Example 2: (correct)
y=0.68
x= Math.round(y* 10);
x = x/10;
result x=0.7
thanks for your time.
Math.round returns variable of type long (see: Javadoc), which means that the division by 10 is performed on a long variable resulting in another long variable - that's why you lose the precision.
To make it calculate on it as on double and return double - you have to cast the result of Math.round like this:
x= ((double)Math.round(y* 10))/10;
Have you tried to explicitly specify double in your calculation:
x = ((double)Math.round( y * 10.0)) / 10.0;
Math.round returns a long....
It's hard to tell from your snippets, because they don't include variable types, but it's likely to be integer division that's killing you. When you divide two integers x and y, where x < y, you get zero:
int x = 4;
int y = 10;
int z = x/y; // this is zero.
y=0.68
x= (Math.round(y* 10)) <--- Evaluated as int since Math.round returns int /10; <-- integer division
result x=0
y=0.68
x= Math.round(y* 10) <-- x is stored as double
x = x/10; <-- double division
result x=7
I guess it's because Math.round returns either a long or an int, depending on whether y is double or float. an then you have an integer division.
in the second example x is already a double and that's why you have a double division.
When you write:
double x = (Math.round(y* 10))/10;
(Math.round(y* 10)) is a long (= 7), which you divide by 10, that gives another long (= 0). The result is then converted back to a double and stored in x.
In your second snippet:
double x = Math.round(y* 10);
This is equal to 7 and converted into a double. x / 10 is then a double operation that returns 0.7.

Categories

Resources