为什么math.ceil返回浮点数? [英] Why does math.ceil return a float?

查看:209
本文介绍了为什么math.ceil返回浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么要使用Python的math.ceil ()和math.floor()操作返回浮点数而不是整数?

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

来自math.ceil ...

数学.天花板(x)
   以浮点数形式返回 x 的上限,最小整数值大于或等于 x .

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

为什么他们认为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返回浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆