Python 中的浮点表示错误
我试图理解为什么我们得到浮点数python 中的表示错误。我知道这不是新问题,但老实说,我很难理解它。我正在浏览python的官方文档 http://docs.python.org/tutorial/floatingpoint .html 位于页面底部的“表示错误”部分。
但我无法理解这个表达式 J/2**N 是如何出现的以及为什么在我的解释器中我得到这个值。 0.1--->0.10000000000000001 我发现的最接近的问题是 浮点问题 和 浮点数如何存储在内存中?但无法理解。
谁能用简单的语言详细说明一下吗?感谢任何帮助。 谢谢, 苏尼尔
Possible Duplicate:
How is floating point stored? When does it matter?
Python rounding error with float numbers
I am trying to understand why we get floating point representation error in python. I know this is not new question here but honestly I am finding hard time to understand it. I am going through the official document of python http://docs.python.org/tutorial/floatingpoint.html on section Representation Error at bottom of the page.
But I am not able to get how this expression J/2**N comes into picture and why in my interpreter I am getting this value.
0.1--->0.10000000000000001
The closest question I found is floating point issue and How are floating point numbers are stored in memory? but not able to understand.
Can anyone please in detail and simple language? Appreciate any help.
Thanks,
Sunil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将 0.1 视为计算机的有理数 - 其小数展开不是有限的有理数。
以1/3为例。对于我们人类来说,我们知道它意味着“三分之一”(不多也不少)。但如果我们不带分数地写下来,我们就必须写 0.3333...等等。事实上,我们无法用十进制表示精确的三分之一。因此,有些数字可以用十进制表示法书写,有些数字则不能。对于后者,我们必须使用分数 - 我们可以这样做,因为我们在学校学过数学。
另一方面,计算机使用位(只有 2 位数字:1 和 0),并且只能使用二进制表示法 - 没有分数。由于基数不同(2而不是10),有限有理数的概念有所转移:我们可以用十进制表示法精确表示的数字可能无法用二进制表示法精确表示,反之亦然。对我们来说看似简单的情况(准确地说,1/10=十分之一=0.1)对于 CPU 来说不一定是简单的情况。
You can think of 0.1 being a rational number for a computer - a rational number whose decimal expansion is not finite.
Take 1/3 for instance. For us humans, we know that it means "one third" (no more, no less). But if we were to write it down without fractions, we would have to write 0.3333... and so on. In fact, there is no way we can represent exactly one third with a decimal notation. So there are numbers we can write using decimal notation, and numbers we can't. For the latter, we have to use fractions - and we can do so because we have been taught maths at school.
On the other hand, the computer works with bits (only 2 digits: 1 and 0), and can only work with a binary notation - no fractions. Because of the different basis (2 instead of 10), the concept of a finite rational number is somewhat shifted: numbers that we can represent exactly in decimal notation may not be represented exactly in binary notation, and vice versa. What looks like a simple case for us (1/10=one tenth=0.1, exactly) is not necessarily an easy case for a CPU.