Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible math.ceil() bug

Tags:

python

On Windows 7 Python 3.2, the following:

print(int(math.ceil(24/10)))

gives me '3' as expected.

On Windows Server with Active Python 2.5, it gives me '2'.

What is the issue here and how can I solve it?

Here's my original code:

number_of_pages = int(math.ceil(number_of_rows/number_of_rows_per_page))

Thanks,

Barry

like image 443
Baz Avatar asked Mar 15 '12 19:03

Baz


People also ask

Which library is used for ceil () floor () functions?

The Python ceil() function rounds a number up to the nearest integer, or whole number. Python floor() rounds decimals down to the nearest whole number. Both of these functions are part of the math Python library.

What does ceil () do in Python?

The math. ceil() method rounds a number UP to the nearest integer, if necessary, and returns the result.

Why does ceil return a float?

There are floating point numbers that do not fit into an integer, so the function would fail if it returned an integer. Returning the same type as the parameter ensures the result will fit.

Does Math ceil return int or float?

Description. This function returns a floating-point value representing the nearest whole number that is greater than or equal to the value passed to it. If that value is an integer it will, by definition, be the value math. ceil() returns, albeit as float not an integer.


1 Answers

Python 2.x uses truncating disivion, so the answer to 24/10 is 2. The ceil of 2 is still 2.

The fix is to convert one of the operands to float:

print(int(math.ceil(24.0/10)))
like image 166
Mark Ransom Avatar answered Sep 21 '22 23:09

Mark Ransom