5

Java.

Is there a difference in a way I initialize a variable:

float f = 100; //implies a cast from integer to float

or

float f = 100f; //simply a float initialization

Can the results be different?

Here I tried to do it with a very big floats, but looks like the loss of precision is the same.

float f1 = (float)2000000000;
float f2 = (float)2000000050;
float f3 = 2000000000f;
float f4 = 2000000050f;
System.out.println(f1 + " " + f2 + " " + (f1==f2) + " " + f3 + " " + f4 + " "+ (f3==f4) );

-> 2.0E9 2.0E9 true 2.0E9 2.0E9 true

Any difference with the doubles?

MiamiBeach
  • 3,261
  • 6
  • 28
  • 54
  • There are no doubles. – Axel May 09 '14 at 18:23
  • Possible duplicate of [Declaring floats, why default type double?](http://stackoverflow.com/questions/16369726/declaring-floats-why-default-type-double) – user1803551 May 09 '14 at 18:46
  • 2
    There is a difference between `float f1 = 1.01161128282547f;` and `float f2 = 1.01161128282547;`, if you are interested. Both are straightforward to compile to the same bytecode operations, but the constant `(float) 1.01161128282547` that `f2` receives is different from `1.01161128282547f` that `f1` receives. – Pascal Cuoq May 09 '14 at 19:00
  • @PascalCuoq I assume that's because `float f2 = 1.01161128282547` goes through an extra step; `valueOf` starts with a conceptual infinite-precision float, but your expression for `f1` rounds the infinite-precision to a `float`, and `f2` rounds the infinite-precision to a `double` first and then a `float`. – ajb May 09 '14 at 19:04
  • 2
    @ajb Exactly. The decimal number 1.01161128282547 is one of these numbers so close to the exact middle between two floats that if you first round it to `double`, it changes the result as opposed to directly rounding it to `float`. – Pascal Cuoq May 09 '14 at 19:06
  • See also http://stackoverflow.com/questions/21442286/what-is-the-difference-between-typing-long-x-43-and-long-x-43l-in-java – Raedwald May 10 '14 at 11:47
  • @PascalCuoq: My preferred number of that type is `((1L<<53)+(1L<<29)+1)`, since one can very easily see the effect of rounding to `double` and then `float`. – supercat May 13 '14 at 22:54

1 Answers1

3

I think the results will be the same. The JLS rules for interpreting a floating-point literal refer to the valueOf(String s) method of Float and Double types; the rules for a type conversion from integer to float types are given by JLS 5.1.2. Both refer to "IEEE 754 round-to-nearest mode". So I think it's safe to assume the results are the same.

ajb
  • 31,309
  • 3
  • 58
  • 84