为什么在Python 3中round()和math.ceil()为负数给出不同的值? [英] Why do round() and math.ceil() give different values for negative numbers in Python 3?

查看:177
本文介绍了为什么在Python 3中round()和math.ceil()为负数给出不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Python 3中round()和math.ceil()赋予负数不同的值?

Why do round() and math.ceil() give different values for negative numbers in Python 3?

例如,

round(-5.5) = -6
round(-5.7) = -6
math.ceil(-5.5) = -5
math.ceil(-5.7) = -5

推荐答案

函数执行不同的数学运算:

The functions execute different mathematical operations:

  • round()将浮点值四舍五入为最近的整数.如果两边的两个整数中的任意一个相距相等,则选择偶数.

  • round() rounds a float value to the nearest integer. If either of the two integers on either side are equal distance apart, the even number is picked.

在这里,最近整数始终为 -6 ;对于 -5.5 ,最接近的偶数是 -6 ,而不是 -5 .

Here, the nearest integer is always -6; for -5.5 the nearest even integer is -6, not -5.

math.ceil()返回浮点值小于或等于的最小整数.

math.ceil() returns the smallest integer greater than or equal to the float value.

在这里,输入的下一个整数更大总是 -5 (请记住,负数减小远离零).

Here, the next integer greater than the inputs is always -5 (remember that negative numbers decrease away from zero).

我认为您最大的困惑来自四舍五入规则.如果选择了 -4.5 ,您会看到 round()返回 -4 :

I think the biggest confusion you have comes from the even rounding rule. Had you picked -4.5, you'd have seen round() return -4:

>>> import math
>>> math.ceil(-4.5)
-4
>>> round(-4.5)
-4

来自 round()函数文档:

From the round() function documentation:

如果两个倍数相等地接近,则四舍五入取整为偶数选择(例如, round(0.5) round(-0.5) 0 ,而 round(1.5) 2 ).

将一半舍入到最接近的整数总是必须以某种方式打破平局,并且不同的编程语言并不总是就如何做到这一点达成共识,取整为偶数,因为这种方法具有优势它没有符号偏差,并且在数字的合理分布中将得到相同的平均值.

Rounding half to the nearest integers always has to break the tie somehow, and different programming languages don't always agree on how to do this, the IEEE 754 standard defines 5 different methods. Python 3 uses the IEEE 754 default and rounds halves to even, because this method has the advantage that it is free of sign bias and in reasonable distributions of numbers will result in the same average values.

这篇关于为什么在Python 3中round()和math.ceil()为负数给出不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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