Bit-level Difference between Float and Double

Here is a segment of  C++ code.

#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	double sum1 = 0;
	for (double i=0.01f; i<=1.0f; i+=0.01f) 
	{
		sum1 += i;
		cout << "i=" << i << endl;
	}
	cout << sum1 << endl;	// sum1=50.5,  i=1.00999 99774 247408 < 1.01 
							// 注意:i精确到小数点后7位
	double sum2=0, ii=0.01;
	for (ii=0.01; ii<=1.0; ii+=0.01) 
	{
		sum2 += ii;
		cout << "ii=" << ii << endl;
	}
	cout << sum2 << endl;	// sum2=49.5, ii=1.00000 00000 00000 7 > 1.0 
	cout << ii << endl;		// 注意:ii精确到小数点后15位
	
	return 0;
}

      As  comments say,  sum1 is not equal to sum2. It is because that float and double type object utilize a 32-bit and a  64-bit quantity to approximate to 0.01 separately. The bit representation of the 32-bit quantity is [0011 1100 0010 0011 1101 0111 0000 1010], while the other one is [0011 1111 1000 0100 0111 1010 1110 0001 0100 0111 1010 1110 0001 0100 0111 1011]. They are both IEEE floating-point representation of 0.01.

   With IEEE floating-point format,  the first bit string is equal to 0.009999999776483 as a decimal, and the second one is 0.0100000000000000002081668. For this, 1.0 will never be added to sum2.

   The precision of float and double is decided by their mantissa. For float, 2^23 = 8388608, there are 6 to 7 significant digits; And for double, 2^52=4503599627370496, there are 15 to 16 significant digits.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值