Hoy, he definido dos variables float f1 y f2 . Entonces realizo una adición, "+", operación aritmética y asignar a flotar variable de f .
float f1 = 0.5048076923076923F;
float f2 = 0.5048076923076923F;
float f = f1 + f2;
De acuerdo con esta imagen, todos los valores de punto flotante ( float y dobles ) en una operación aritmética ( +, -, *, / ) se convierten en doble tipo: fuente de imagen: 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?
PS: English isn't my Mother tongue, please forgive me if this question has somes grammar issue. Thanks. :)
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:
- This is only allowed if the expression is not
strictfp
. - These are not the "conversions" that the JLS talks about in JLS 5.6.2.
- Esto todavía contradice lo que el maestro de la OP está diciendo. Él (o ella) establece que los todos los cálculos de punto flotante se realizan utilizando
double
. Los JLS estados que , en determinadas circunstancias , una plataforma de hardware puede utilizar aritmética de precisión extendida (posiblemente con más precisión que el punto flotante de 64 bits), y en otras circunstancias que no deben hacer esto .