先看下一下代码:
int main()
{
printf("sizeof(int) = %d\n",sizeof(int));
printf("sizeof(float) = %d\n",sizeof(float));
return 0;
}
打印结果如下:
同样是占用4字节空间,为何int的表示范围是-2147483648~2147483647;而float类型的表示范围是-3.4*10^38~3.4*10^38;
明显float表示的范围要比int广,这是为何?
因为浮点数(还有double类型的数)表示的数都是不精确的;
举个例子:
int main()
{
printf("%0.50f\n",2.7);
printf("%0.50f\n",0.2);
return 0;
}
其实float和double类型是按照IEEE 754标准进行数据存放的,float中E为8bit,M为23bit,double中E为11bit,M为52bit
那如何确认这类浮点数的精度呢?
For EPSILON, you can use the constants FLT_EPSILON, which is defined for float as 1.192092896e-07F, or DBL_EPSILON, which is defined for double as 2.2204460492503131e-016. You need to include float.h for these constants. These constants are defined as the smallest positive number x, such that x+1.0 is not equal to 1.0. Because this is a very small number, you should employ user-defined tolerance for calculations involving very large numbers.
按照定义:
#define DBL_EPSILON 2.2204460492503131E-16
#define FLT_EPSILON 1.19209290E-07F
#define LDBL_EPSILON 1.084202172485504E-19
和我们常说的float精度7-8位,double精度16-17bit一致;那具体为什么是取这些值呢?
https://www.jianshu.com/p/306ef3d99b81 这篇文章里面有很详细的描述,建议参考http://en.wikipedia.org/wiki/Single_precision