在浮动的最大值 [英] maximum value in float

查看:209
本文介绍了在浮动的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关下面的循环,我期待的输出为和= 20e6 但输出和= 1.67772e + 07

For the following loop, I was expecting output to be sum = 20e6 but the output is sum = 1.67772e+07.

float sum=0.0f;
for(i=0;i<20e6;i++)
    sum = sum + 1.0f;
printf("sum = %g\n", sum);

问1:为什么是浮动不能持有价值超过 1.67772e07 更大?

Question 1: Why sum being float cannot hold values greater than 1.67772e07?

问题2:如果我更改了循环语句总和=总和+ 1.001f; 总和那么最终值为 2.32229e + 07 。为什么在总和值这种差异?

Question 2: If I change the statement in the loop to sum = sum + 1.001f; then final value of sum is 2.32229e+07. Why is this difference in the value of sum?

问题3:我们可以控制在上面,这样我们就可以使用float比 1.67772e07 值越大循环这种行为,同时还递增通过1.0F?

Question 3: Can we control this behaviour in the loop above such that we can use float for values bigger than 1.67772e07 while still incrementing by 1.0f?

推荐答案

在某一点上,最接近重presentable值 X + 1.0F X 本身。达到这一点后,由于此舍入误差您的循环不会引起款项的任何进一步增加

At some point, the closest representable value to x + 1.0f is x itself. After that point is reached, due to this rounding error your loop won't cause any further increase in sum.

作为一个例子,你可以观察用科学记数法具有固定数量的显著数字这种效果。例如,用4显著附图:

As an illustration, you can observe this effect using scientific notation with a fixed number of significant figures. For example, with 4 significant figures:

    0 = 0.000e0
    1 = 1.000e0
    2 = 2.000e0
    3 = 3.000e0

...

    9 = 9.000e0
   10 = 1.000e1
   11 = 1.100e1

...

  99 = 9.900e1
 100 = 1.000e2
 101 = 1.010e2

...

  999 = 9.990e2
 1000 = 1.000e3
 1001 = 1.001e3

...

 9999 = 9.999e3
10000 = 1.000e4

如果你添加一个,你应该得到 1.0001e4 ,但由于只有4显著数字是preserved,存储的值 1.000e4 ,例如: 10000 + 1 =在本系统中10000,并继续增加只是永远重复此计算不改变的结果。

and if you add one more, you should get 1.0001e4, but since only 4 significant digits are preserved, the stored value is 1.000e4, e.g. 10000 + 1 = 10000 in this system, and continuing to increment just repeats this calculation forever without changing the result.

您code工作方式完全相同,不同的是浮动使用二进制浮点,作为科学记数法不小数。但显著二进制数字的数量仍然有限,当增加一个不会改变的那些显著数字之一,停止增加。

Your code works exactly the same way, except that float uses binary floating-point, not decimals as scientific notation does. But the number of significant binary digits is still limited, and when adding one more doesn't change one of those significant digits, sum ceases to increase.

这是稍微复杂一些,因为二进制,正确的结果就是中途二重presentable号之间,所以四舍五入既可以发生向下的或向上的,在这种情况下,你问加1,但实际上得到的结果高2。在任何情况下,一旦重新presentable值之间的距离为4,试图增加一个将没有任何效果。

It's somewhat more complicated, because with binary, the "correct" result is midway between two representable numbers, so rounding could either occur downward or upward, in which case you asked to add 1 but actually get a result 2 higher. In any case, once the distance between representable values becomes 4, trying to add one will have no effect.

这篇关于在浮动的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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