3 / 2 = 1.0? really? [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Integer Division, How do you produce a double?
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat output...
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.

In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f; // I believe the f and d for float and double are optional, but
double d = 1.0d; // I wouldn't bet on what the default is if they're omitted...
Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.
To work around this, you should (as many others have suggested) instead calculate the quotient of
(the double 3) / (the double 2)
or, in Java syntax,
double wang = 3.0 / 2.0;
1 Source: The Java Tutorial from Oracle

Integer division of 3 by 2 is equal to 1 with residue of 1. Casting to double gives 1.0

3 and 2 are integer constants and therefore 3 / 2 is an integer division which results in 1 which is then cast into a double. You want 3.0 / 2.0

Try: double wang = 3.0 / 2.0;

That's the expected behaviour. "3" and "2" are both int values, and when you perform 3 / 2 the result will also be an int value which gets rounded down to 1. if you cast both to double before you perform the division then you'll get the result that you expect:
double wang = (double)3 / (double)2;

Related

Java casting (cast operator expressions) [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14

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]

How do math equations work in Java?

When I do something like this
int test = 5 + 3 * (4 - 1) / 2;
I get 9. I suspected this was because int rounds down. However, when I do this
float test = 5 + 3 * (4 - 1) / 2;
I also get 9. However, when I do this
float test1 = 5;
float test2 = 4.5;
float test = test1 + test2;
Test finally outputs 9.5. Could someone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.
In your second example, although you are assigning the result to a variable of type float, the calculation itself is still performed exactly the same way as the first example. Java does not look at the destination variable type to determine how to calculate the right hand side. In particular, the subexpression 3 * (4 - 1) / 2 results in 4.
To fix this, you can use floating point literals instead of all integers:
float test = 5 + 3 * (4 - 1) / 2.0f;
Using 2.0f triggers floating point calculations for the arithmetic expression.
Although you represent the result of 5 + 3 * (4 - 1) / 2 in a float, the actual evaluation is done with the precision of an integer, meaning that the division of 9 / 2 returns 4 rather than the 4.5 you would receive if they were evaluated as floats.
Expressions have their own type. So start with:
5 + 3 * (4 - 1) / 2
Each value has its own type. This type happens to be int, so this is the same as:
((int)5) + ((int)3) * (((int)4) - ((int)1)) / ((int)2)
Making it clearer that we're dealing with ints. Only after this is evaluated as 9 does it get assigned to a float.
The short answer is that integer types operate on modular arithmetic, with modulus 1, and discard the remainder.
Since you cast test as an integer, modular arithmetic is employed with modulus 1 (e.g. 9.5 mod 1),
int test = 5 + 3 * (4 - 1) / 2;
With a 32-or-64 bit float this would give 9.5; however, because you have cast test as an int, the remainder is discarded, and the value referenced by test is 9.

Understanding Casting in Java

this is my first post here and i like to thank all the people that can help me with this simple question: how the casting works in java?
I made this very simple class:
public class test {
public static void main ( String[] args )
{
System.out.println((short)(1/3));
System.out.println((int)(1/3));
System.out.println((float)(1/3));
System.out.println((double)(1/3));
}
}
and this piece of software gives me this output when executed ( official JDK 6 u26 on a 32 bit machine under linux )
0
0
0.0
0.0
the problem, or the thing that i don't understand if you would, is that the last 2 results are 0.0, i was expecting something like 0.3333333, but apparently the cast works in another way: how?
thanks
PS
I'm not so familiar with the english language, if i made some errors i apologize for this
First, the expression 1/3 is executed. This expression means "integer division of 1 by 3". And its result is the integer 0. Then this result (0) is cast to a double (or float). And of course it leads to 0.0.
You must cast one of the operands of the division to a double (or float) to transform it into a double division:
double d = ((double) 1) / 3;
or simply write
1.0 / 3
If you use the operator / on integer values, the result will be typed as an integer.
You will have to force either 1 or 3 to a floating point value - try writing 1.0/3 instead of 1/3.
In the last 2 cases you first compute 1/3, which is 0. Then you cast it to a float/double.
Use:
((float)1)/3
int is coverted into double.
(1/3) is of type int so answer will be 0.
Now 0 is casted to double or float so it has become 0.0
You need to cast the operands, not the result. This will yield the output you expected:
System.out.println(((short) 1 / (short) 3));
System.out.println((1 / 3));
System.out.println(((float) 1 / (float) 3));
System.out.println(((double) 1 / (double) 3));
Because you have the 1/3 in parentheses, it uses integer division then casts to the type specified. It would evaluate to .3333333 if you used 1.0/3.0 or (float)1/3. 1 and 3 are integer literals, so results from division will be truncated. To use float and double literals put an f or d at the end of the number (1.0f, 1.0d). Casting affects the value after it, so if your value is in parentheses, it will evaluate that, then make the cast.

Categories