NT_SYSTEM
NT_SYSTEM

Reputation: 377

Notation of double floating point values in C and C++

What's the notation for double precision floating point values in C/C++?

.5 is representing a double or a float value?

I'm pretty sure 2.0f is parsed as a float and 2.0 as a double but what about .5?

http://c.comsci.us/etymology/literals.html

Upvotes: 2

Views: 9767

Answers (2)

Tomek
Tomek

Reputation: 4659

It's double. Suffix it with f to get float.

And here is the link to reference document: http://en.cppreference.com/w/cpp/language/floating_literal

Upvotes: 9

aka.nice
aka.nice

Reputation: 9382

Technically, initializing a float with a double constant can lead to a different result (i.e. cumulate 2 round off errors) than initializing with a float constant.

Here is an example:

#include <stdio.h>
int main() {
    double d=8388609.499999999068677425384521484375;
    float f1=8388609.499999999068677425384521484375f;
    float f2=8388609.499999999068677425384521484375;
    float f3=(float) d;
    printf("f1=%f f2=%f f3=%f\n",f1,f2,f3);
}

with gcc 4.2.1 i686 I get

f1=8388609.000000 f2=8388610.000000 f3=8388610.000000

The constant is exactly in base 2:

100000000000000000000001.011111111111111111111111111111

Base 2 representation requires 54 bits, double only have 53. So when converted to double, it is rounded to nearest double, tie to even, thus to:

100000000000000000000001.10000000000000000000000000000

Base 2 representation requires 25 bits, float only have 24, so if you convert this double to a float, then another rounding occur to nearest float, tie to even, thus to:

100000000000000000000010.

If you convert the first number directly to a float, the single rounding is different:

100000000000000000000001.

As we can see, when initializing f2, gcc convert the decimal representation to a double, then to a float (it would be interesting to check if the behaviour is determined by a standard).

Though, as this is a specially crafted number, most of the time you shouldn't encounter such difference.

Upvotes: 1

Related Questions