python中的math.ceil,为什么Python的math.ceil()和math.floor()操作返回浮点数而不是整数?...

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

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

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

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

EDIT:

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.

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: `math.floor()` 函数是 Python 标准库 `math` 的一个函数,用于将一个数向下取整到最近的整数。具体使用方法如下: ```python import math x = 3.6 y = 5.9 print(math.floor(x)) # 输出 3 print(math.floor(y)) # 输出 5 ``` 在上面的示例,`math.floor()` 函数将 `x` 向下取整为最近的整数 3,将 `y` 向下取整为最近的整数 5,并将结果输出到控制台。 ### 回答2: math.floor()是Python标准库的一个函数,用于向下取整。它的作用是返回小于或等于传入参数的最大整数math.floor()函数需要传入一个数值作为参数,可以是整数浮点数或者是包含数字的字符串。它返回的结果是一个整数,该整数不大于传入参数的值,并且比传入参数的值小。 举个例子,如果我们使用math.floor(3.7),函数会返回3,因为3是小于或等于3.7的最大整数。同样地,如果我们使用math.floor(-2.3),函数会返回-3,因为-3是小于或等于-2.3的最大整数math.floor()通常用于一些需要精确数值的场景,比如货币计算、数据分析等。在一些商业或科学计算,我们需要确保计算结果具有精确性,所以使用向下取整可以避免结果出现误差。 需要注意的是,math.floor()返回的是一个整数,即使传入的是浮点数。所以不要将向下取整的结果与原始数值进行比较,因为它们的数据类型是不同的。 总之,math.floor()是一个常有用的函数,可以用于对数值进行向下取整,以保证计算结果的准确性和精确性。 ### 回答3: math.floor() 是Python用于向下取整的函数。它的作用是返回不大于传入参数的最大整数math.floor()的参数可以是整数浮点数或者其他可以转化为数字的数据类型。当参数是整数时,返回值即为该整数本身。当参数是浮点数时,返回值为不大于该浮点数的最大整数。当参数是其他数据类型时,函数会尝试将其转化为数字类型,并按照上述规则进行取整。 例如,对于math.floor(5.6),返回值为5;对于math.floor(3),返回值为3;对于math.floor(-2.3),返回值为-3。 math.floor()在一些需要对数值进行下取整的场景很有用。例如,在金融计算,我们可能需要对货币进行向下取整,确保不超过实际金额。又或者,在统计分析,我们可能需要将浮点数数据转化为整数,以便于计算和比较。 需要注意的是,math.floor()只能进行向下取整操作,不能对小数部分进行四舍五入或向上取整。若要进行其他类型取整操作,可以使用math.ceil()向上取整函数或round()进行四舍五入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值