Considerations for division use in Python

  • 2020-04-02 13:58:26
  • OfStack

This article illustrates the considerations of division in Python, which is a very important technique and has a good reference value for Python programming. 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)    # 1.5 
avg(1, 2, 3, 4) # 2.5 

The source is just to demonstrate the use of variable-length arguments, but in Python's 2.7.1 interpreter, I got a different result from the comment


>>> def avg(first, *rest): 
...   return (first + sum(rest)) / (1 + len(rest)) 
...  
>>> avg(1, 2) 
1 
>>> avg(1, 2, 3, 4) 
2 

It's obvious that the data behind the decimal point is truncated, and I remember that two integers are divided by each other, and "//" is supposed to be the integer, am I wrong?


>>> def avg(first, *rest): 
...   return (first + sum(rest)) // (1 + len(rest)) # change '/' to '//' 
...  
>>> avg(1, 2) 
1 
>>> avg(1, 2, 3, 4) 
2 

If I change "/" to "//", I get the same result. I remember correctly that "//" is indeed rounded, but why is the result of "/" truncated?

I tested the same procedure in the 3.4.1 interpreter and got the expected 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 '//' 
...  
>>> avg(1, 2) 
1 
>>> avg(1, 2, 3, 4) 
2 

You can see that in the 3.4.1 interpreter, the result of "/" retains the decimal place, while "//" is the result of rounding

A search turned up the question on stackoverflow: how do you force division in Python to result in floating point Numbers? Note that this is for version 2.x, there is no such problem with 3.x
The first two solutions to the answer, both 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:


c = a / float(b)

I believe that the examples described in this article will be helpful to your Python programming.


Related articles: