Search code examples
pythondivisionfloor

Division by 3 in Python


I am new to Python and while experimenting with operators, I came across this:

>>> 7.0 / 3
2.3333333333333335

Shouldn't the result be 2.3333333333333333 or maybe 2.3333333333333334. Why is it rounding the number in such a way?

Also, with regard to floor division in Python 2.7 my results were:

>>> 5 / 2
2
>>> 5 // 2
2
>>> 5.0 / 2
2.5
>>> 5.0 // 2
2.0

So my observation is that floor division returns the integer quotient even in case of floating numbers, while normal division return the decimal value. Is this true?


Solution

  • Take a look at this 0.30000000000000004.com

    Your language isn't broken, it's doing floating point math. Computers can only natively store integers, so they need some way of representing decimal numbers. This representation comes with some degree of inaccuracy. That's why, more often than not, .1 + .2 != .3.