Python Forum
Why is this happening? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why is this happening? (/thread-30301.html)



Why is this happening? - taner7 - Oct-14-2020

Hi,
Newly learning Python through Linkedin Learning and I got the following result when I make multiplication. Why is this happening, any idea? I have experienced this oddness in some other multiplications but not with the numbers with 2 decimal..

Thanks

[Image: Zh2JPl1_d.webp?maxwidth=728&fidelity=grand]


RE: Why is this happening? - bowlofred - Oct-14-2020

Many numbers can't be exactly represented by the standard floating point representation.  You should write your code in such a way that this limitation doesn't cause problems for you.   See the python FAQ entry on this.


RE: Why is this happening? - sblancov - Oct-14-2020

Yes:

https://docs.python.org/3/tutorial/floatingpoint.html

In [5]: 0.1 + 0.1 + 0.1
Out[5]: 0.30000000000000004


RE: Why is this happening? - Skaperen - Oct-14-2020

try to work out what that number is in base two.  the trouble is that 3.2 takes an infinite number of bits to do it.  but computers limit the number of bits per number.  the bits get set to a number that needs no more bits than the maximum.  it gets set to the number closest to what was wanted.  when that number gets printed, it is printing that very close number the best it can (most numbers can't even be printed in base ten, such as 1/3).