0
float f = 3.4028235E38F;

will compile fine but

float f = 3.4028235E38;

throws this error:

 possible loss of precision

in this code:

http://ideone.com/0Hu3dA

I would have expected just the opposite as floating point literals are by default double and should be more precise.

mark_huffington
  • 464
  • 1
  • 3
  • 12
  • 4
    Yes, `double` is more precise than `float`. So when you convert from `double` to `float`, you may lose information. So the conversion is explicit. Not sure there's much more to say than that... – Jon Skeet Sep 13 '13 at 14:05
  • 2
    float is not wider than double. It's the other way round. Edit: oh, you removed that phrase from the question. – BalusC Sep 13 '13 at 14:06
  • @mark_huffington your image analogy is a good one, but your conclusion is incorrect. You can think of a double as a 100x100 image, and a float as a 50x50 image. Sure, you can use both to store a picture of the same object, but the 100x100 one will be more detailed. So if you convert it to 50x50, you will lose resolution. In the same way, a float and a double can both be used to represent some floating point number, but the double can do so more precisely. – Tim S. Sep 13 '13 at 14:14
  • The extra bits in floating point numbers, unlike integers, is not just used to extend the minimum and maximum values. It adds both range (minimum/maximum are bigger) to the number, but it also adds more precision within that range. See https://en.wikipedia.org/wiki/Single_precision_floating-point_format and https://en.wikipedia.org/wiki/Double_precision_floating-point_format for more details. – Tim S. Sep 13 '13 at 14:16
  • It just so happens in this example that `3.4028235E38` will NOT loose precision as it is a perfect representation, but none the less, the error is correct. – mark_huffington Sep 13 '13 at 14:19

1 Answers1

4

Because floating point numbers are by default of type double. To make it a float you append an F. You are getting error in the below assignment:

float f = 3.4028235E38;

because a double as more precision than a float. So, there is a possible loss of precision.

I would have expected just the opposite as floating point literals are by default double and should be more precise.

Let's check the binary representation of your number till double precision:

0x47EFFFFFE54DAFF8 =    01000111 11101111 11111111 11111111 
                        11100101 01001101 10101111 11111000

Now since float is a single precision 32-bit floating point value. It can't store all the double values, which are double precision 64-bit floating point values.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 1
    "floating point literals are by default double", so setting it to a float will lose precision. Setting it to double f = blahblah won't. – doctorlove Sep 13 '13 at 14:05