Basic python arithmetic - division

I have two variables: count, which is the number of my filtered objects and the constant value per_page. I want to divide the score by per_page and get an integer value, but it doesn't matter what I try - I get 0 or 0.0:

>>> count = friends.count() >>> print count 1 >>> per_page = 2 >>> print per_page 2 >>> pages = math.ceil(count/per_pages) >>> print pages 0.0 >>> pages = float(count/per_pages) >>> print pages 0.0 

What am I doing wrong and why does math.ceil give a floating point number instead of int?

+6
python math
source share
6 answers

Python performs integer division when both operands are integers, which means that 1 / 2 is basically "how many times 2 goes into 1", which of course is 0 times. To do what you want, convert one operand to float: 1 / float(2) == 0.5 , as you expect. And of course, math.ceil(1 / float(2)) will give 1 as you expect.

(I think this division behavior changes in Python 3.)

+16
source share

Integer division is the default for the / operator in Python <3.0. It has a behavior that seems a little strange. He returns the dividend without a remainder.

 >>> 10 / 3 3 

If you are using Python 2.6+, try:

 from __future__ import division >>> 10 / 3 3.3333333333333335 

If you are using a lower version of Python, you will need to convert at least one of the numerator or denominator to a float:

 >>> 10 / float(3) 3.3333333333333335 

In addition, math.ceil always returns a float ...

 >>> import math >>> help(math.ceil) ceil(...) ceil(x) Return the ceiling of x as a float. This is the smallest integral value >= x. 
+6
source share

They are integers, so count/per_pages is zero before the functions ever get the opportunity to do anything other than this. I am not a Python programmer, but I know that (count * 1.0) / pages will do what you want. This is probably the right way to do this.

edit - yes see @mipadi and float(x) answer

0
source share

From Python documentation (math module) :

math.ceil(x)

Return ceiling x as a float, the smallest integer value greater than or equal to x.

0
source share

because, as you configured it, the operation is performed and then converted to an attempt to float.

 count = friends.count() print count per_page = float(2) print per_page pages = math.ceil(count/per_pages) print pages pages = count/per_pages 

Converting count or per_page to float, all its future operations should be able to perform divisions and end with integers

0
source share
 >>> 10 / float(3) 3.3333333333333335 >>> #Or >>> 10 / 3.0 3.3333333333333335 >>> #Python make any decimal number to float >>> a = 3 >>> type(a) <type 'int'> >>> b = 3.0 >>> type(b) <type 'float'> >>> 

A better solution might be to use from __future__ import division

0
source share

All Articles