问题描述
来自math.ceil
...
为什么他们认为float
更好?毕竟,数字的ceil根据定义是整数,需要实数的运算可以轻松地从int
转换为float
,但不一定要相反,就像[0] * ceil(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)
.
推荐答案
有些浮点数不适合整数,因此如果返回整数,该函数将失败.返回与参数相同的类型可确保结果合适.
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.
尽管Python可以表示非常大的整数,但情况并非总是如此.我不知道何时引入长整数,但是直到2.4版之前,它们还没有很好地与常规整数混合.我以为math.ceil
在引入长整数之前就已经存在了,但是我没有足够的Python历史可以肯定.
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.
从浮点到整数的转换也可以带来一些惊喜.通过将ceil
函数与int
转换分开,可以很容易地看出哪部分是令人惊讶的.
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
这篇关于为什么math.ceil返回浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!