常规浮点数学查询 [英] General floating-point maths query

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

问题描述

好的,所以我得到一些数字不能正确地用二进制表示,就像1/3不能完全用十进制表示一样.

Okay so I get that some numbers can't be represented properly in binary just like 1/3 can't be fully represented in decimal.

那么当我console.log(0.3)返回0.3时,结果又如何呢? 但是当我console.log(0.1 + 0.2)时,它返回0.30000000000000004

So how come when I console.log(0.3) it returns 0.3 but when I console.log(0.1 + 0.2) it returns the 0.30000000000000004

为什么仅输出0.3却不能算出错误(即使是偶数)呢?

How come it is accounting for the error (if it even is) when simply outputting 0.3 but doesn't when the addition occurs?

推荐答案

假设我们以小数点近似1/3和2/3.

Suppose we approximate 1/3 and 2/3 in decimal.

1/3 = 0.333
2/3 = 0.667

我们加上1/3 + 1/3:

and we add 1/3+1/3:

1/3+1/3 = 0.333 + 0.333 = 0.666

我们没有得到2/3的近似值.将1/3舍入到我们可以用十进制表示的位数时,得出的数字不会等于2/3舍入时的一半.

We didn't get our approximation of 2/3. Rounding 1/3 to something we can represent in decimal didn't produce a number equal to half of what we got when we rounded 2/3.

同样的事情也发生在二进制文件中.我们将0.1和0.2四舍五入为可以用二进制表示的数字,但是近似值的总和与近似值0.3所得到的略有不同.我们得到了更高的结果,结果显示为0.30000000000000004.

The same thing happens in binary. We round 0.1 and 0.2 to numbers we can represent in binary, but the sum of the approximations is slightly different from what we get if we approximate 0.3. We get something a bit higher, and the result is displayed as 0.30000000000000004.

这篇关于常规浮点数学查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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