Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why will Java convert the double to float type in this situation?

Tags:

java

eclipse

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:
enter image description here

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
image

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? picture source: https://www.homeandlearn.co.uk/java/short_float_variables.html

like image 683
Bruce Avatar asked Jan 27 '23 15:01

Bruce


1 Answers

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.
  • This still contradicts what the OP's teacher is saying. He (or she) states that the all floating point calculations are done using 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.
like image 112
Stephen C Avatar answered Jan 31 '23 20:01

Stephen C