添加双重问题 [英] Problem adding double

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

问题描述

我需要平均得3分:

总和必须为27.3且平均值必须为9.1

sum must be 27.3 and average must be 9.1

但总和= 27.299999且平均值为9.09999

but sum= 27.299999 and average is 9.09999

我可以不圆,我必须断绝平均值。

我该怎么做才能避免这个问题?谢谢




推荐答案

不多,你看,这是一个表示问题。

Not much, you see, this is a problem of representation.

为了开始这个解释,让我们看一下类似的基数为10的情况。

To start of this explanation, lets look at a similar situation in base 10.

如果你看数字1/3,你会怎么用十进制来写?它将是0.3333333 ...(3是重复出现的)因为在基数10中,不可能完全代表1/3。 2 / 3s,1 / 9,2 / 9,4 / 9和更多数字也是如此。因为
无法准确表示数字的想法不应该让你感到惊讶。

If you look at the number 1/3, how would you write it in decimal? It would be 0.3333333... (3 is recurring) because in base 10, it is not possible to represent 1/3 exactly. The same is true with 2/3s, 1/9, 2/9, 4/9 and so many more numbers. The idea of being unable to represent numbers exactly shouldn't be that surprising to you.

现在关于为什么这很重要,浮点数以二进制形式存储。这意味着您将无法准确表示不同的数字集。重复的数字,比如这些情况下的9s,是无法准确表示
a数的标志。

Now as to why this matters, floating point numbers are stored in binary. This means that there will be a different set of numbers that you can't represent exactly. Recurring numbers, like the 9s in these cases, are a hallmark of not being able to represent a number exactly.

所以让我们看一下小数点后的数字,看看如何接近0.3我们真的可以得到二进制。

So lets look at the number after the decimal point and see how close to 0.3 we really can get in binary.

点后的第一个数字的值为1/2或0.5,所以这不能是1,第二个数字是1/4或0.25因此这是我们的起点。

The first digit after the point has a value of 1/2, or 0.5, so this can't be 1, the second digit is 1/4, or 0.25 so this is our starting point.

0.01 = 1/4 = 0.25

0.01 = 1/4 = 0.25

下一步是

0.011 = 1/4 + 1/8 = 0.375

0.011 = 1/4 + 1/8 = 0.375

这不对,所以第三个数字必须为0

this isn't right, so the third digit must be 0

0.010

接下来是0.0101 = 1/4 + 1/16 = 0.3125

Next is 0.0101 = 1/4 + 1/16 = 0.3125

再次,这太高了所以这不对,第四个数字必须为0

again, this is too high so this isn't right, the fourth digit must be 0

0.0100

如果我们遵循这种模式,我们得到的是

If we follow this pattern, what we get is

0.010011001100110011 ...

0.010011001100110011...

这是一个有规律重复数字的数字,所以0.3不能用二进制表示。所以任何以.3结尾的数字都不可表示。

This is a number with regularly repeating digits, so 0.3 is not representable in binary. So any number that ends with a .3 is not representable.

如果你用9.1做同样的事情,你也应该发现0.1不能用二进制表示。

If you try the same thing with 9.1, you should also find that 0.1 is not representable in binary.

这是一个令人震惊的事实,你首先发现浮点数与你习惯的不同。

This is one of those shocking truths where you first find out that floating point numbers aren't the same as you are used to.


这篇关于添加双重问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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