2

Possible Duplicate:
Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

From the Python documentation of math.ceil...

math.ceil(x)
    Return the ceiling of x as a float, the smallest integer value greater than or equal to x.

Why did they consider float to be better? After all, the ceil of a number is by definition an integer and operations requiring real numbers can easily convert from int to float, but not necessarily the other way around, like in the case of [0] * ceil(x).

Community
  • 1
  • 1
Paul Manta
  • 30,618
  • 31
  • 128
  • 208

2 Answers2

1

This is an oddity that is present in all math libraries. One point to make is that floating-point numbers representing integers are different from integers (they might exceed even the range of a 64-bit integer, for example). Usually you continue to use those numbers in a calculation, for example. And then they have to be converted to floating-point again, anyway.

Joey
  • 344,408
  • 85
  • 689
  • 683
0

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.

Edit: Even though Python can represent very large integers, this wasn't always the case. I don't know when long integers were introduced, but until version 2.4 they didn't intermix with regular integers very well. I assume that math.ceil was around before long integers were introduced, but I don't have enough Python history to know for sure.

The conversion from floating point to integer can also hold some surprises. By keeping the ceil function separate from the int conversion it's easy to see which part is the source of the surprise.

>>> math.ceil(1e23)
1e+23
>>> int(math.ceil(1e23))
99999999999999991611392L
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622