Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python 2.7 report incorrect ceiling value? [duplicate]

I recently transitioned one script to use Python 2.7 from 3.4 (at the request of a colleague), and I'm finding that the math.ceil function does not work the same...

When I divide 5/2 and round it up with math.ceil(), I expect to get math.ceil(5/2) = 3.

Given the following code:

from __future__ import print_function
import math

a = 5
b = 2
c = math.ceil(a/b)

print("Ceiling output: {}".format(c))

Python 2.7 will report 2 as the answer, Python 3.4 reports 3 as expected.

Why is this?

I know I can get 2.7 to work if I cast a and b as float:

c = math.ceil(float(a)/float(b)

However, casting the division won't work either:

c = math.ceil(float(a/b))

How does 3.4 work around this?

Finding this makes me question how much math I need to re-check in the 2.7 version of the script.

like image 233
Catsunami Avatar asked Jun 07 '26 17:06

Catsunami


2 Answers

It's because the division operator / is integer division in Python 2.7. Note that the function arguments are fully evaluated before the function call, so math.ceil was actually an innocent bystander here.

math.ceil(5/2)  # same as math.ceil(2)!

To get the Python 3 behaviour in 2.7, use a future statement:

from __future__ import division
like image 52
wim Avatar answered Jun 10 '26 05:06

wim


This is because / in Python 2 is regular integer division.

If you want the / operator to behavethe way it does in Python 3 then add this line to your imports from __future__ import division.

Also, note that if you wanted to regular integer division in Python 3 use // instead of /.

after you add the import you will find that

In [16]: from __future__ import division

In [17]: a = 5

In [18]: b = 2

In [19]: import math

In [20]: c = math.ceil(a/b)

In [21]: c
Out[21]: 3.0
like image 37
Srini Avatar answered Jun 10 '26 05:06

Srini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!