2-3 浮点数的秘密

先看下一下代码:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值