Today, I defined two float variable f1 and f2. Then I perform an addition, "+", arithmetic operation and assign to float variable f.
float f1 = 0.5048076923076923F;
float f2 = 0.5048076923076923F;
float f = f1 + f2;
This is the output:
According to this picture, All floating point values (float and double) in an arithmetic operation (+, −, *, /) are converted to double type:
picture source: http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html
I found an identical question but it hasn't explain why. Why doesn't eclipse have any issue tips? Is it the reason why the value of "f1 + f2" is a float type? And, why will Java auto convert the double to float type if like the above picture saying?
You seem to be saying that there is a conversion to float
in the following.
float f1 = 0.5048076923076923F;
float f2 = 0.5048076923076923F;
float f = f1 + f2;
In fact, there is no conversion. The values are all float
.
In particular, the literal 0.5048076923076923F
is a float
. The trailing F
makes it a float
. If you want a double literal, leave off the F
or replace it with D
.
When your teacher says "all floating point values are converted to double
" he is wrong. The JLS says (in effect) that a numeric primitive operand will be converted to double
when the other operand is a double
. If both operands are float
, then the operation will performed using single-precision floating point arithmetic.
The JLS reference is JLS 5.6.2: Binary Numeric Promotion.
It has been pointed out that there may be additional conversions happening at the hardware level. For example, the JLS says this:
Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.
However:
strictfp
. double
. The JLS states that under certain circumstances, a hardware platform may use extended precision arithmetic (possibly with more precision than 64 bit floating point), and in other circumstances it must not do this.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