Reputation: 3020
I have read this many times in C programming language that by default any floating-point value is of type double not float, So when we write.
float PI = 3.14;
then PI will have a value 3.14-some_small_value, this is due to precision consideration, because 8 bytes values is now assigned to 4 bytes variable. Can anyone please explain that how does it happen in terms of memory, or internally how these values are changed.
Upvotes: 2
Views: 309
Reputation: 320681
In this case the change you observe does not have much to do with conversion from 8-byte format to 4-byte format. Your PI
will be different from 3.14
regardless of whether you declare it as float
or double
. Value 3.14
is impossible to represent precisely in binary floating-point format. 4, 8 or 1234 bytes is still not enough to build a precise binary representation of 3.14
, since in traditional binary floating-point format this representation is infinitely long.
The exact binary representation of 3.14
is
11.001000111101011100001010001010001111010... = 11.0(01000111101011100001010001)
meaning that the 01000111101011100001010001
part is repeated again and again indefinitely. When you use float
the whole representation is truncated (or rounded) to the capacity of float
, while in case of double
it is truncated to the capacity of double
. For this reason, any floating-point type will represent 3.14
only approximately. double
will be more precise than float
, but still not absolutely accurate.
This rounding is exactly what turns 3.14
into 3.1400001049041748046875
in case of float
and into 3.140000000000000124344978758017532527446747
in case of double
(results from GCC compiler). Your compiler might use a different rounding strategy, resulting in slightly different values.
Upvotes: 4