谁能解释这浮点怪事给我吗? [英] Can anyone explain this floating point weirdness to me?

查看:210
本文介绍了谁能解释这浮点怪事给我吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过这样的一个浮动的所有可能值试图循环

I was trying to loop through all possible values of a float like this:

float i = 0.0F;
float epsilon = float.Epsilon;
while (i != float.MaxValue) {
    i += epsilon;
}

而深远的价值2.3509887E-38F后,不再增加。

but after reaching the value 2.3509887E-38F it stops increasing.

float init = 2.3509887E-38F;
float f = (init + float.Epsilon);
Console.WriteLine(f == init);

我只是好奇,谁能解释究竟为什么?

I'm just curious, can anyone explain exactly why?

所以,我能舍入误差前加小量为float 16777216次,而且这个数字看起来非常熟悉(2 ^ 24)。

So, I can add epsilon to a float 16777216 times before the rounding error, and that number looks awfully familiar (2^24).

推荐答案

有很多非常毛茸茸的思想在这里。浮点数是不是IM precise。没有可以。这是一个确定性的系统,就像任何其他的计算机上。

There's a lot of very wooly thinking here. Floating point numbers are not "imprecise". There is no "may". It's a deterministic system, like anything else on a computer.

不要来分析什么是通过看小数重presentations回事。这种行为的来源完全是显而易见的,如果你看一下二进制或十六进制这些数字。让我们用二进制:

Don't to analyze what's going on by looking at decimal representations. The source of this behavior is completely obvious if you look at these numbers in binary or hexadecimal. Let's use binary:

float.Epsilon is b1.0 x 2^-149
2.3509887E-38 is b1.0 x 2^-125

如果我们添加这两个数字加在一起,无限precise(未取整)之和为:

If we add these two numbers together, the infinitely precise (unrounded) sum is:

b1.000 0000 0000 0000 0000 0000 1 x 2^-125

请注意,这个和的尾数为25位宽(我的分组二进制数字为每组四个,使他们更容易来算)。这意味着它不能被重新psented在单precision $ P $,所以这个总和的结果是的此值,但是代替于此值的四舍五入的到在关闭重presentable 浮动。这两个最接近的再presentable号码是:

Note that the significand of this sum is 25 bits wide (I've grouped the binary digits into sets of four to make them easier to count). This means that it cannot be represented in single-precision, so the result of this sum is not this value, but instead this value rounded to the closes representable float. The two closest representable numbers are:

b1.000 0000 0000 0000 0000 0000 x 2^-125
b1.000 0000 0000 0000 0000 0001 x 2^-125

我们的人数刚好一半在他们之间。由于您没有设置舍入模式在你的程序中,我们在默认的舍入模式,这就是所谓的舍入到最近,领带,甚至。由于这两个选项都同样紧密,领带通过选择一个其最低位是零破碎。因此,2 ^ -125 + 2 ^ -149舍入为2 ^ -125,这也是为什么,它停止增加。

Our number is exactly halfway in between them. Since you haven't set the rounding mode in your program, we are in the default rounding mode, which is called "round to nearest, ties to even". Because the two options are equally close, the tie is broken by choosing the one whose lowest-order bit is zero. Thus, 2^-125 + 2^-149 is rounded to 2^-125, which is why "it stops increasing".

这篇关于谁能解释这浮点怪事给我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆