Python中的浮点表示错误 [英] Floating point representation error in Python

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

问题描述


可能重复:

如何存储浮点数?什么时候重要?

Python四舍五入错误浮点数


我想了解为什么我们在蟒蛇。我知道这不是新的问题,但老实说,我很难理解它。我正在通过Python的官方文档 http://docs.python.org/tutorial/floatingpoint



但我无法得到这个表达式J / 2 ** N如何进入画面为什么在我的口译员中,我获得了这个价值。
0.1 ---> 0.10000000000000001
我发现的最接近的问题是
浮点问题浮点数如何存储在内存中?但无法理解。



任何人都可以请详细和简单的语言?感谢任何帮助。
谢谢,
Sunil

解决方案

你可以想到0.1是一个有理数的计算机 - 有理数,其十进制扩展不是有限的。

以1/3为例。对于我们人类来说,我们知道它意味着三分之一(不多也不少)。但是,如果我们把它写下来,而不是分数,我们将不得不写0.3333 ...等等。事实上,我们没有办法用十进制符号表示三分之一。所以,我们可以用十进制表示法来编写数字,而我们不能使用数字。对于后者,我们必须使用分数 - 我们可以这样做,因为我们在学校教数学。另一方面,计算机的工作与位(只有两个数字:1和0),只能使用二进制符号 - 没有分数。由于不同的基础(2而不是10),有限有理数的概念有些偏移:我们可以精确地用十进制表示的数字不能完全用二进制表示,反之亦然。对于我们来说,看起来像一个简单的例子(1/10 =十分之一= 0.1,对于CPU来说)并不一定是一个简单的例子。


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

解决方案

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.

这篇关于Python中的浮点表示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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