Last Updated: February 25, 2016
·
4.534K
· bnlucas

Math and Int/Float in Python

If you're transitioning from a language like PHP to Python, such as myself... There is something you need to know about using math.ceil with integers.

Test case, pagination:

import math

import requests

response = requests.get('http://website.com/api', params={'page': 1})
result = response.json()

result['info'] = {u'num_results': u'182', u'limit': u'100', u'offset': u'0', u'page': u'1'}

Coming from PHP, I would expect the following to work:

num_results = int(result['info']['num_results'])
limit = int(result['info']['limit'])

pages = int(math.ceil(num_results / limit))

print pages # You get a result of '1', not 2 like you should.

The Python way:

num_results = float(result['info']['num_results'])
limit = float(result['info']['limit'])

pages = int(math.ceil(num_results / limit))

print pages # You get a result of '2'

Even though the numbers are technically integers, you would expect math.ceil to convert the result into a float and you are good to go. But, in Python, you must first convert them to floats in order to get a proper result from math.ceil. The same thing goes with all int math operations that will result in a float:

>>> float(182 / 100) # gives you 1.0
>>> float(182) / float(100) # gives you 1.82

1 Response
Add your response

The problem is not math.ceil, but rather that in Python 2 division between integers. So if in Python 2 you do: 182 / 100 you actually get 1. In the second snippet ceil actually gets 1 as argument: it cannot convert the single numbers to floats because it gets the result as argument. You can avoid that (on Python 2) by adding at the top of the file:

from __future__ import division

and you would get what you would expect. This is the default in Python 3: 182 / 100 gives 1.82.

over 1 year ago ·