The examples in this paper explain the considerations of the use of division in Python, which is a very important technique, and it is very useful for Python program design. The specific analysis is as follows:
Here's an example:
def avg (First, *rest): return (first + sum (rest))/(1 + len (rest)) # Sample Use AVG (1, 2)
The source program just to demonstrate the use of variable-length parameters, but in the Python 2.7.1 interpreter, I get the result is not the same as the result of the comment
>>> def avg (First, *rest): ... return (first + sum (rest))/(1 + len (rest)) ...
It can be clearly seen that the data after the decimal point is truncated, I remember dividing two integers, "//" should be the rounding, I remember wrong?
>>> def avg (First, *rest): ... return (first + sum (rest))//(1 + len (rest)) # change "/' to '//' ...
Change the "/" to "//", the result is the same, "//" is indeed to take the whole point I remember correctly, but why "/" The result is also truncated?
The same procedure I tested in 3.4.1 's interpreter and got the desired result:
>>> def avg (First, *rest): ... return (first + sum (rest))/(1 + len (rest )) ... >>> avg (1, 2) 1.5 >>> avg (1, 2, 3, 4) 2.5 >>> def avg (First, *rest): ... return (first + sum (rest))//(1 + len (rest)) # change "/' to '//' ...
You can see that in 3.4.1 's interpreter, the "/" result retains the decimal place, and "//" is the result of rounding.
After searching, I found the question on StackOverflow: How does the Force division in Python result in a floating-point number? Note that this is for the 2.x version, 3.x there is no such problem
The first two solutions to the answer are good:
Method 1:
Method 2:
Similar to the practice in the C language:
c = a/float (b)
I believe that the examples described in this article will be helpful to everyone's Python programming.