Why does math.ceil return a float? [duplicate]

不打扰是莪最后的温柔 提交于 2019-12-06 09:33:16

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!