Do you know float division and integer division in python?

Since python2.2, there are two division operators: "/" and "//". The biggest difference between the two is:

By default in versions before python2.2 and versions before 3.0 after python2.2, the division made by "/" is a floating point number when two or more numbers appear and the result is expressed as a floating point number that float division
"//" is not doing the same division, "//" regardless of any two numbers are divisible results to prevail, no fractional part is processed directly abandoned, which is divisible by law
following is the author The data tested in the compiler, the tested version is python2.7

on"/":

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 of the divisors is a floating point number, then the result obtained 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 two integers are divided, the result is still an integer, but. If a floating-point number is divided by a non-floating-point number, the result will be a floating-point number. However, the result of the calculation is to ignore the fractional part. The result of the operation is similar to the division of two integers, but a floating-point number is obtained. In addition, "//" is no exception for two floating-point numbers.

How to divide labor between "/" and "//"

By default, these two operators have great overlaps. For example, when both numbers are integers, there is no difference in 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, "//" is used for integer division, we can make the following statement at the beginning of the program:

from future import division

The result of the test after the declaration (the version tested below is python2.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 know that after making this statement, "/" will perform float division instead of integer division.

It should also be noted that in pyhton3, "/" means float division, no need to introduce the module, even if the numerator and denominator are both int, the return will also be a floating point number

What Doesn’t Kill Me Makes Me Stronger

Guess you like

Origin blog.csdn.net/waitingwww/article/details/107138872