c/c++ notation of double floating point values

こ雲淡風輕ζ 提交于 2019-11-29 17:21:28
Tomek

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!