What happens when we assign a float value to a double variable? [duplicate]

4
class Test {
    public static void main (String[] args){
        double pi = 3.1415f;
        System.out.println(pi);
    }
}

When compiling and executing the above code, I get the return: 3.1414999961853027
This is not a question for solving a problem.
I just want to understand what's going on here ...

    
asked by anonymous 29.08.2016 / 17:07

2 answers

5

There is no magic going on here. It is only the form that information is being displayed that ends up confusing the user (developer). This is the way that float is implemented, when you write 3.1415f this is not the actual value that will be applied to the variable, it is not exactly the value found in memory according to the float implementation. You can perform some tests:

float a = 3.1415f;
float b = 3.1414999961853027f;

System.out.println("a = " + a); // a = 3.1415
System.out.println("b = " + b); // b = 3.1415
System.out.println(a == b); // true

The value displayed for both cases receiving a "rounding", but the actual value found in the variable is not 3.1415f . This "problem" is not very common to find when working with only floats , but when there is value coercion from float to double people notice this difference because double ends up displaying all the information, thus rendering the values different (when in fact they are not).

double c = a;
System.out.println("c = " + c); // c = 3.1414999961853027

You can see here a few more tests proving that both values are exactly the same.

NOTE: This is not only characteristic of Java , several languages implement this rule, and developers often suffer from this when they need a lot of precision. C # implements the same rules for float and double , when something needs a lot of precision as monetary values they have a decimal implementation to meet those demands. Other languages such as JavaScript have only one implementation to represent numbers, and they end suffering from this , ranging from problems accurately to representing large numbers, requiring libraries to solve the problem.

    
29.08.2016 / 17:32
0

It turns out that the variables have different sizes:

Float Represents numbers in standard precision floating-point notation of 32 bits in accordance with the IEEE 754-1985 standard. The smallest positive value reportable by this type is 1.40239846e-46 and the largest is 3.40282347e + 38

Double Represents numbers in double-precision normalized floating-point notation of 64 bits in accordance with the IEEE 754-1985 standard. The smallest positive representable value is 4.94065645841246544e-324 and the largest is 1.7976931348623157e + 308

When you assign a value double to float it truncates the value to the supported size, half the size, decreasing the precision of the value. Just that.

See more information at: link

    
29.08.2016 / 17:21