I want to calculate the volume of a sphere using a Java program. So, I used
double result = 4/3*Math.PI*Math.pow(r,3);
This formula gives the wrong answers it seems.
Like Java program opt 4/3, but if I change it to
double result= Math.PI*Math.pow(r,3)*4/3;
it gives me the correct answer. Does any one know what is going on?
This has to do with the order in which casting occurs in Java (or C for that matter).
For the full details on operator precedence, see http://introcs.cs.princeton.edu/java/11precedence/.
In your first case, since the multiply and divide operators are computed from left to right, the first operation java interprets is 4/3. Since both operands are integer, java computes an integer division, the result of which is 1.
In your second case, the first operation is the double multiply: (Math.PIMath.pow(r,3)). The second operation multiplies a double (Math.PIMath.pow(r,3)) by an integer (4). This is performed by casting 4 to a double and performing a double multiply. Last, java has to divide a double (Math.PI*Math.pow(r,3)*4) by an integer (3), which java performs as a double division after casting 3 to a double. This gives you the result you expect.
If you want to correct your first answer, cast 3 to double first:
4/ (double)3
and you will get the result you expect.
The difference in the outcome is due to operator precedence. In Java, multiplication and division have equal precedence, and therefore are evaluated from left to right.
So, your first example is equivalent to
double result = (4/3)*Math.PI*Math.pow(r,3);
Here, 4/3 is a division of two integers, and in Java, in such cases integer division is performed, with outcome 1. To solve this, you have to explicitly make sure that one or both of the operands is a double:
double result = (4.0/3.0)*Math.PI*Math.pow(r,3);
Your second example, however, is equivalent to
double result = (Math.PI*Math.pow(r,3)*4)/3;
Here, the Math.PI*Math.pow(r,3)*4
part is evaluated to a double, and thus we have no integer division anymore and you get the correct result.
4/3
is a division between two int
, so Java assumes that the result is also an int
(in this case, this results in the value 1
). Change it to 4.0/3.0
and you'll be fine, because 4.0
and 3.0
are interpreted as double
by Java.
double result = 4.0 / 3.0 * Math.PI * Math.pow(r,3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With