开发者

Floating point representation error in Python [duplicate]

开发者 https://www.devze.com 2023-04-10 18:05 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How is floating point stored? When does it matter?
This question already has answers here: Closed 11 years ago.

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 k开发者_如何学Cnow 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号