当Python 3中尾随的小数点大于等于0.5时,math.ceil()和round()之间的算法区别是什么? [英] What is the algorithmic difference between math.ceil() and round() when trailing decimal points are >= 0.5 in Python 3?

查看:170
本文介绍了当Python 3中尾随的小数点大于等于0.5时,math.ceil()和round()之间的算法区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中,尾随小数点> = 0.5时math.ceil()和round()之间的算法区别是什么?

What is the algorithmic difference between math.ceil() and round() when trailing decimal points are >= 0.5 in Python 3?

例如,

round(9.5) = 10
round(9.67) = 10
math.ceil(9.5) = 10
math.ceil(9.5) = 10

推荐答案

来自文档

[...]如果两个倍数相等接近,则向偶数取整 选择(例如,round(0.5)和round(-0.5)均为0,并且 round(1.5)是2).

[...] if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

但是,math.ceil将始终四舍五入". IE.大于或等于输入的最小整数.

However, math.ceil will always "round" up. I.e. the smallest integer greater than or equal to the input.

此外,当对负数执行时,roundmath.ceil有很大差异.

Moreover, round and math.ceil differ greatly when executing on negative numbers.

>>> math.ceil(-2.8)
-2
>>> round(-2.8)
-3

这篇关于当Python 3中尾随的小数点大于等于0.5时,math.ceil()和round()之间的算法区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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