This article illustrates the considerations of division in Python, which is a very important skill, and has good reference value for Python programming. The specific analysis is as follows:
Now look at the following example:
def avg (*rest): Return (A/A (rest))
/(1 + len (rest))
# Sample Use
avg (1, 2) # 1.5
avg (1 , 2, 3, 4) # 2.5
The source program is just to demonstrate the use of variable-length parameters, but in the Python 2.7.1 interpreter, I get a different result than the annotation.
>>> def avg (*rest):
... return (i + sum (rest))/(1 + len (rest))
...
>>> avg (1, 2)
1
>>> avg (1, 2, 3, 4)
2
It is obvious that the data after the decimal point has been truncated, I remember two integer division, "//" should be the rounding, I remember wrong?
>>> def avg (*rest):
... Return (A. (rest))//(1 + len (rest)) # change '/' to '//'
...
>>> avg (1, 2)
1
>>> avg (1, 2, 3, 4)
2
"/" changed to "//", the result is the same, "//" is indeed to take this point I am not mistaken, but why "/" The result is truncated?
The same program I tested in 3.4.1 's interpreter and got the desired result:
>>> def avg (*rest):
... return (i + sum (rest))/(1 + len (rest))
...
>>> avg (1, 2)
1.5
>>> avg (1, 2, 3, 4)
2.5
>>> def avg (i, *rest):
... Return (A. (rest)) //(1 + len (rest)) # change '/' to '//'
...
>>> avg (1, 2)
1
>>> avg (1, 2, 3, 4)
2
You can see in 3.4.1 's interpreter that the result of "/" keeps the decimal bit, and "//" is the result of rounding
After the search, I found the question on StackOverflow: How do you force division in Python as a floating-point number? Note that this is for the 2.x version, there is no such problem in 3.x
The first two solutions to the answer are very good:
Method 1:
>>> from __future__ Import Division
>>> A = 4
>>> b = 6
>>> c = a/b
>>> C
0.66666666666666663
Method 2:
Similar to the practice in C language:
I believe the example described in this article will help you with your Python programming.