浮点数也有假的吗?

博客讲述在MSDN Newsgroups上看到的浮点数累加问题,代码累加0.1时出现0.8000001等误差。MVP解释0.1不能精确表示为float类型,只有能写成m*2^e形式的数才不会累加出错。试验发现VC6也有类似问题,提醒使用浮点数要小心。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是昨天在MSDN Newsgroups上看到的,问题描述如下:

The following code:

float someFloat = 0;
for(int x = 1; x <= 10; x++)
{
 someFloat += .1F;
 Console.WriteLine(someFloat.ToString());
}


Returns:
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8000001
0.9000001
1


WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY, WHY!!! What happened to
the nice and rounded 0.8 and 0.9? I know that the float variable is prone to
rounding issues but come on!! I am just adding a 0.1. I haven't even gotten
to where it needs to start rounding!! What's going on???? Is this normal? It
probaly is, isn't it?

Rene遇到了这个问题,累加过程中出现了0.8000001的错误,四舍五入后肯定是错不了的,但是如果出现在需要准确计算的时候,这样的错误或许会留下隐患,what`s going on ? 看看作为MVP的Bruno Jouhier的回答:

The problem is that 0.1 cannot be represented **exactly** as a float
(surprise!)

Float (and double) can only represent exactly numbers that can be written as
m * 2^e where m and e are integers (possibly negative).
Numbers like 0.5, 0.25, 0.125 or 0.875 are exactly representable as floats
(1*2^-1, 1*2^-2, 1^2-3, 7*2^-3) but 0.1 is not (its binary representation is
infinite)!

So, 0.1f is only an approximation of 0.1 and the error will accumulate when
you add.

惊讶吧?0.1不能被正确的表现为float类型,只有能被写成m*2^e(m和e都是int型的,负数也可以)表示的才是真正意义上的浮点数,这样的数才不会造成我们使用时累加时出现error accumulate的情况。

然后我在试验了一下,的确是这样的,但是用VC6确没有这个错误。不死心,扩大一下范围,循环100次,每次加0.01,结果VC6在0.83开始出现了小错误,0.84成了0.8399999了。

记住哦,在使用浮点数的时候要小心了呀!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值