Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic python arithmetic - division

I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 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 math.ceil gives float number instead of int ?

like image 831
tom_pl Avatar asked Jul 29 '10 22:07

tom_pl


People also ask

How do you code division in Python?

To perform integer division in Python, you can use // operator. // operator accepts two arguments and performs integer division. A simple example would be result = a//b . In the following example program, we shall take two variables and perform integer division using // operator.

What is the arithmetic operator for divide in Python?

Division Operator : In Python, / is the division operator.

How do you divide 2 in Python?

Integer division takes two numbers and divides them to give a result of a whole number. In Python 3, integer division (or floor division) uses the double front-slash // operator. In Python 2, integer division uses the single front-slash / operator.

How do you divide 3 numbers in Python?

The division operator "/" works as integer division if both inputs are integers. Therefore, 5/3 returns 1. You must supply a floating point number ('float') with decimal points if an answer other than a whole number is desired: 5.0/3 returns 1.666666.


2 Answers

Python does integer division when both operands are integers, meaning that 1 / 2 is basically "how many times does 2 go into 1", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5, as you're expecting. And, of course, math.ceil(1 / float(2)) will yield 1, as you expect.

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

like image 138
mipadi Avatar answered Sep 22 '22 01:09

mipadi


Integer division is the default of the / operator in Python < 3.0. This has behaviour that seems a little weird. It returns the dividend without a remainder.

>>> 10 / 3
3

If you're running Python 2.6+, try:

from __future__ import division

>>> 10 / 3
3.3333333333333335

If you're running a lower version of Python than this, you will need to convert at least one of the numerator or denominator to a float:

>>> 10 / float(3)
3.3333333333333335

Also, 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.
like image 27
Tim McNamara Avatar answered Sep 23 '22 01:09

Tim McNamara