Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why 1 // 0.05 results in 19.0 in python?

I'm a new to python and I found a confusing result when using Python3.5.1 on my mac, I simply ran this command in my terminal

    1 // 0.05

However, it printed 19.0 on my screen. From my point of view, it should be 20. Can someone explain what's happening here? I've already known that the '//' is similar to the math.floor() function. But I still can't get across to this.

like image 986
Jian Guo Avatar asked Mar 09 '16 16:03

Jian Guo


People also ask

Why does Python have rounding errors?

It's a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.

What is the result of 10 3 in Python?

10/3 returns 3.333333 instead of 3, 6/3 returns 2.0 instead of 2.

How do you write 1e 6 in Python?

To write a float literal in E notation, type a number followed by the letter e and then another number. Python takes the number to the left of the e and multiplies it by 10 raised to the power of the number after the e . So 1e6 is equivalent to 1×10⁶.

How many decimals does Python use?

Python Decimal default precision The Decimal has a default precision of 28 places, while the float has 18 places. The example compars the precision of two floating point types in Python.


Video Answer


2 Answers

Because the Python floating-point literal 0.05 represents a number very slightly larger than the mathematical value 0.05.

>>> '%.60f' % 0.05
'0.050000000000000002775557561562891351059079170227050781250000'

// is floor division, meaning that the result is the largest integer n such that n times the divisor is less than or equal to the dividend. Since 20 times 0.05000000000000000277555756156289135105907917022705078125 is larger than 1, this means the correct result is 19.

As for why the Python literal 0.05 doesn't represent the number 0.05, as well as many other things about floating point, see What Every Computer Scientist Should Know About Floating-Point Arithmetic

like image 68
Steve Jessop Avatar answered Oct 31 '22 20:10

Steve Jessop


0.05 is not exactly representable in floating point. "%0.20f" % 0.05 shows that 0.05 is stored as a value very slightly greater than the exact value:

>>> print "%0.20f" % 0.05
0.05000000000000000278

On the other hand 1/0.05 does appear to be exactly 20:

>>> print "%0.20f" % (1/0.05)
20.00000000000000000000

However all floating point values are rounded to double when stored but calculations are done to a higher precision. In this case it seems the floor operation performed by 1//0.05 is done at full internal precision hence it is rounded down.

like image 20
Duncan Avatar answered Oct 31 '22 20:10

Duncan