Detailed explanation of float division and integral division in python

  • 2021-07-24 11:18:42
  • OfStack

Since python 2.2, there are two kinds of division operators: "/" and "//". The biggest difference between the two is:

By default for python before 2.2 and python after 2.2 and before 3.0, "/" is divided as a floating-point number when one floating-point number occurs, that is, float division

The division rules of "//" are different. No matter any number appears in "//", the division result shall prevail, and the decimal part shall not be processed and directly discarded, that is, the division method

The following is the data I tested in the compiler, and the tested version is python 2.7

About "/":


>>> 3/2
1
>>> 3/2.0
1.5
>>> 3.0/2
1.5
>>> 10/3.0
3.3333333333333335

From the above example, we can conclude that as long as one number in the divisor is a floating-point number, the result is also a floating-point number

The following is about "//":


>>> 3//2
1
>>> 3//2.0
1.0
>>> 3.0//2
1.0
>>> 3.0//2.0
1.0

From the above example, we can see that if you divide two integers, you will still get an integer, but. If a floating-point number is divided by a non-floating-point number, it will still be a floating-point number, but the result of the calculation is to ignore the decimal part. The result of the operation is similar to dividing two integers, but one floating-point number is obtained. In addition, "//" is no exception for two floating-point numbers.

How to divide the work between "/" and "//"

By default, the two operators overlap a lot; For example, when both numbers are integers, there is no difference between the results of the two operations. If you want to have a clear division of labor between these two in python. That is, "/" can be used for float division and "//" can be used for division. We can make the following declaration at the beginning of the program:


from __future__ import division

The results of the post-declaration test (the version of the following test is python 2.7)


>>> from __future__ import division
>>> 3/2
1.5
>>> 3.0/2
1.5
>>> 3/2.0
1.5
>>> 3.0/2.0
1.5
>>> 3//2
1
>>> 3.0//2
1.0
>>> 3.0//2.0
1.0
>>> 3//2.0
1.0
>>> -11/2
-5.5

Above, we can see that after making this statement, "/" will do float division instead of integral division.

It should also be noted that in pyhton3, "/" means float division, so there is no need to introduce modules. Even if the numerator and denominator are int, the return will be a floating point number


Related articles: