为什么Python的math.ceil()和math.floor()操作返回浮点数而不是整数? [英] Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

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

问题描述

有人可以解释这一点吗?(直接来自 docs -强调我的):

Can someone explain this (straight from the docs- emphasis mine):

math.ceil(x)返回x 的上限为浮点数,最小的 integer 值大于或等于x.

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

math.floor(x)返回x 的底数作为浮点数,最大的 integer 值小于或等于x.

math.floor(x) Return the floor of x as a float, the largest integer value less than or equal to x.

为什么.ceil.floor按照定义应该计算整数时会返回浮点数?

Why would .ceil and .floor return floats when they are by definition supposed to calculate integers?

关于它们为什么应该返回浮点数的问题,这引起了一些很好的争论,而当我

Well this got some very good arguments as to why they should return floats, and I was just getting used to the idea, when @jcollado pointed out that they in fact do return ints in Python 3...

推荐答案

浮点数的范围通常超过整数的范围.通过返回浮点值,函数可以为超出整数可表示范围的输入值返回一个有意义的值.

The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.

考虑:如果floor()返回整数,floor(1.0e30)应该返回什么?

Consider: If floor() returned an integer, what should floor(1.0e30) return?

现在,尽管Python的整数现在具有任意精度,但并非总是这样.标准库函数是等效的C库函数的精简包装.

Now, while Python's integers are now arbitrary precision, it wasn't always this way. The standard library functions are thin wrappers around the equivalent C library functions.

这篇关于为什么Python的math.ceil()和math.floor()操作返回浮点数而不是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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