c#浮点循环,意外的结果 [英] c# floating point for loop, unexpected results
问题描述
pre $
for(float i = -1; i <1; i + = .1F)
Console.WriteLine(i);
输出:
-1
<-0> -0.9
<-0> -0
-0.6999999
-0.5999999
-0.4999999
- 0.3999999
-0.2999999
-0.1999999
-0.99999993
$ b $ 7.450581E-08
$ b $ 0.1000001
$ b
$ b $ 0.3000001
0.4000001
0.5000001 $ b $ 0.6000001
0.7000001
0.8000001
0.9000002
我确定这个问题一定是以某种形式问过的,但是我无法快速找到它。 :)
答案归结为浮点数的表示方式。您可以通过维基百科进入技术细节,但简单地说,十进制数不会必然有一个精确的浮点数表示...
浮点数(基2浮点数,无论如何双打和浮点数)工作[0]的方式是加权1/2来达到你想要的。所以0.5只是1/2。 0.75是1/2 + 1/4等等。
问题出现了,在这个二进制系统中,你永远不能代表0.1 2所以最好的电脑可以做的是存储一个非常接近,但不是0.1的数字。通常你不会注意到这些差异,但他们在那里,有时候你可以让自己表现出来。有很多方法来处理这些问题,你使用哪一个是非常依赖于你实际上在做什么。
[0]在稍微handwavey接近足够的方式
Can anyone explain to me why this program:
for(float i = -1; i < 1; i += .1F)
Console.WriteLine(i);
Outputs this:
-1
-0.9
-0.8
-0.6999999
-0.5999999
-0.4999999
-0.3999999
-0.2999999
-0.1999999
-0.99999993
7.450581E-08
0.1000001
0.2000001
0.3000001
0.4000001
0.5000001
0.6000001
0.7000001
0.8000001
0.9000002
Where is the rounding error coming from??
I'm sure this question must have been asked in some form before but I can't find it anywhere quickly. :)
The answer comes down to the way that floating point numbers are represented. You can go into the technical detail via wikipedia but it is simply put that a decimal number doesn't necessarily have an exact floating point representation...
The way floating point numbers (base 2 floating point anyway like doubles and floats) work [0]is by adding up powers of 1/2 to get to what you want. So 0.5 is just 1/2. 0.75 is 1/2+1/4 and so on.
the problem comes that you can never represent 0.1 in this binary system without an unending stream of increasingly smaller powers of 2 so the best a computer can do is store a number that is very close to but not quite 0.1.
Usually you don't notice these differences but they are there and sometimes you can make them manifest themselves. There are a lot of ways to deal with these issues and which one you use is very much dependant on what you are actually doing with it.
[0] in the slightly handwavey close enough kind of way
这篇关于c#浮点循环,意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!