Java integer-double division confusion [duplicate] - java

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
Program 1
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
VS.
Program 2
int sum= 30
double avg =sum/4.0 // Prints lns 7.5
Is this because the '4' in program 1 is acting as a literal integer? so 30/4 would give me 7. However since this data type is a double, we need to add a .0 to end. so '7.0'
Program 2 has 4.0 which is acting as a literal double. an int/double would always give double because it more precise. so we get '7.5'. I don't understand what double data type is doing to the result though.. it really doesn't need to do anything since the conditions of the double data type are already satisfied.(have the most precise result out of the computation).
Am I wrong? I encourage you to correct me! This is how I learn.. :)

In your first example:
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
sum is an int, and 4 is also an int. Java is dividing one integer by another and getting an integer result. This all happens before it assigns the value to double avg, and by then you've already lost all information to the right of the decimal point.
Try some casting.
int sum = 30;
double avg = (double) sum / 4; // result is 7.5
OR
int sum = 30;
double avg = sum / 4.0d; // result is 7.5

This is an integer division (because it involves two integers)
int sum = 30;
double avg = (sum / 4); // result is 7
Integer division, will round down to the nearest integer.
However, this is a double division (because 4.0 is a double)
int sum= 30
double avg = (sum/4.0) // result is 7.5
This is the expected behaviour, and the conversion are all well defined. No need to guess. Take a look at the java docs about conversion.
A widening 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

In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions.
Both 30 and 4 are integer values, so if you try to divide them, integer division is used.
But if you try either 30.0/4 or 30/4.0 then the result will be 7.5 because you will be using floating-point division.
The declared type of the variable avg has no influence on the result. The decimal part is lost during the division, and not when you assign the value to the variable.

Image taken from : http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html
Refer above URL for more clear explanation.

PROGRAM 1
In Java, when you do a division between two integers, the result is an integer. So when you do sum/4, the result is the integer 7. Then you assign that integer to a double variable, so that 7 turns into 7.0.
PROGRAM 2
In Java, when you do a division between an integer and a double, the result is a double. So when you do sum/4.0, the result is the double 7.5. Then you assign that to a double variable, so it's still 7.5.
So the problem is not how println prints the variables, but how division works in Java

Related

Difference between number/10 and number*0.1 in java

I've been working on an interview question for 1.5 hours and could not find the bug in my Java program.
And then I found what the problem was, which I don't understand (don't pay attention to the values, there were others, it's about the types):
int size=100;
Integer a=12;
if(a >= size/10)...
//didn't work
is different than
if(a >= size*0.1)...
//worked
I understand that there is a conversion, but still, how is it possible that with a=12, if(a>=size/10) returns false?
Why is that?
/10 is integer division. While *0.1 first converts the first operand to a double and performs a floating point multiplication.
If you use the /10, and the operand is 14, it will result in 1 indeed, 14/10=1.4 but integer division rounds this down. Thus 29/10=2.
If you use *0.1, the Java compiler will first convert the value of size to a double, thus 14.0 and then muliplies it with 0.1 resulting in 1.4.
On the other hand it's not all beaty that comes out of floating points. float and double can't represent every integer, and round off after computation.
For the given values for size however, it will result in the effect because 100 is a multiple of 10 and a float or double is capable of representing any integer value in the range from zero to hundred.
Finally /10 is not always an integer division: if the first operand is a floating point (e.g. 14.0d/10), the compiler will convert this to a floating point division.
Short version:
int/int is an integer division that rounds down to the nearest (lower) integer.
int*double is a double multiplication that - with rounding off errors - results in the floating point value, nearest to the correct result (with decimal digits).
I just tested here:
public class a {
public static void main(String[] args) {
int size = 100;
int a = 12;
System.out.println((a >= size / 10) ? "OK" : "Failed?");
}
}
And it worked. I don't think this is your real problem. Probably it's in another part of your code.

Dividing error in java language

I have a simple java program that does not operate the way that I think it should.
public class Divisor
{
public static void main(String[] args)
{
int answer = 5 / 2;
System.out.println(answer);
}
}
Why is this not printing out 2.5?
5 / 2 is integer division (you're even storing it in an integer variable), if you want it to be 2.5, you need to use floating point division:
double answer = 5.0 / 2.0;
Integer division is always going to be equal to normal mathematical division rounded down to the nearest integer.
Java has integer division which says: integer divided by integer results in integer. 2.5 cannot be represented with integer so the result is floored to 2.0. Moreover, you store the result in integer.
If you need floating point division you can cast one of operands to double and change answer type to double as well. You use literal values here, so changing 5 to 5. makes this literal value double.
In the end the following should work for you:
double answer = 5. / 2;
Note, you don't even need a zero sign after a dot symbol!

Java float not acting correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
I am having this problem:
float rate= (115/100);
When I do:
System.out.println(rate);
It gives me 1.0
What... is the problem?
115 and 100 are both integers, so will return an integer.
Try doing this:
float rate = (115f / 100f);
You're performing integer division (which provides an integer result) and then storing it in a float.
You need to use at least one float in the operation for the result to be the proper type:
float rate = 115f / 100;
float rate= (115/100);
Does the following things:
1) Performs integer division of 115 over 100 this yields the value 1.
2) Cast the result from step 1) to a float. This yields the value 1.0
What you want is this:
float rate = 115.0/100;
Or more generally, you want to convert one of the pieces of your division into a float whether that is via casting (float)115/100 or by appending a decimal point to one of the two pieces or by doing this float rate = 115f / 100 is completely up to you and yields the same result.
In order to perform floating-point arithmetic with integers you need to cast at least one of the operands to a float.
Example:
int a = 115;
int b = 100;
float rate = ((float)a)/b;
use float rate= (float)(115.0/100); instead
It is enough to put float rate = 115f / 100;
The problem you have is that your dividend and divisor are declared as integer type.
In mathematic when you divide two integer results only with remainder. And that is what you assign to your rate variable.
So to have the result as you expected, a remainder with fraction (rational numbers). Your dividend or divisor must be declared in a type with precision.
Base two known types with precision are float (Floating point) and double (Double precision).
By default all numbers (integer literals for purists) written in Java code are in type int (Integer). To change that you need to tell the compiler that a number you want to declare should be represent in different type. To do that you need to append a suffix to integer literal.
Literals for decimal types:
float - f or F; 110f;
double - d or D 110D;
Note that when you would like to use the double, type you can also declare it by adding a decimal separator to literal:
double d = 2.;
or
double d = 2.0;
I encourage you to use double type instead of float. Double type is more suitable for most of modern application. Usage of float may cause unexpected results, because of accuracy problem that in single point calculation have bigger impact on result. Good reading about this “What Every Computer Scientist Should Know About Floating-Point Arithmetic”.
In addition on current CPU architecture both float and double have same performance characteristic. So there is not need to sacrifice the accuracy.
A final note about floating point types in is that non of them should be use when we write a financial application. To have valid results in this matter, you should always used [BigDecimal]

Beginners Java Question (int, float)

int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema
So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?
When you divide two ints (eg, 2 / 3), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0.
You need to force Java to perform a double division by casting either operand to a double.
For example:
fractionCinema = (cinema / (double)total) * 100;
Try this instead:
int cinema, total;
int fractionCinema;
fractionCinema = cinema*100 / total; //percent cinema
For example, if cinema/(double)total is 0.5, then fractionCinema would be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.
Addendum
As pointed out by #user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:
fractionCinema = (cinema*100 + 50) / total; //percent cinema
When you divide two ints, Java will do integer division, and the fractional part will be truncated.
You can either explicitly cast one of the arguments to a double via cinema/(double) total or implicitly using an operation such as cinema*1.0/total
As some people have already stated, Java will automatically cut off any fractional parts when doing division of integers. Just change the variables from int to double.

Error with division using double type in Java

Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365; is telling me that answer is 0. Or any other combination of double for that matter, its just truncating the decimal and I just don't know why.
364/365 performs integer division (truncates the decimal).
Try double answer = 364.0/365; to force it to perform floating point division.
Something like:
double days_in_year = 365;
double answer = 364/days_in_year;
would work as well, since one of the operands isn't an integer.
You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:
double answer = 364d / 365d;
More info here:
http://mindprod.com/jgloss/division.html
You need do do double division. Right now Java is interpreting it as integer division and returning the truncated int.
What you need is:
double answer = 364 / 365.0;
or
double answer = 364 / (double) 365;
The reason is that the default type of integer literals in java is int and all the result of all int based arithemetic is type casted back to int. Hence though your answer is 0.997, when it is typecasted back it becomes 0:
(int)0.997 = 0
So you can do like this:
364.0/365.0
or
((float)364)/365
All the above answers are right, would just like to add that it is all about GIGO.
double answer = 364/365;
in above code double type implies only to answer variable and arithmetic expression has both operands of int type. So the output of the arithmetic expression is also int type which is then through auto up-casting to double type gives output 0.0, just like below examples:
double ans = 4.0/0;
the above code will give output Infinity as one of the operand is Floating-point number so through auto type-casting 0 is converted to 0.0 and the result is as per the Floating-point datatype.
whereas
double ans = 4/0;
will give java.lang.ArithmeticException: / by zero exception at runtime since both the operands are of datatype int and so the output is as per the Integer datatype irrespective of ans variable datatype being double.

Categories