python3.3.2我对函数“round”有正确的理解吗?

2024-05-23 23:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,但我真的不知道python 3.3.2 doc中round的定义是什么意思:

round(number[, ndigits])
Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero. Delegates to number.__round__(ndigits).

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits 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). The return value is an integer if called with one argument, otherwise of the same type as number.

我不知道为什么10和pow的倍数。在

在阅读了以下示例之后,我认为round(number,n)的工作原理如下:

如果设number123.456,则n为{}

  1. round将得到两个数字:123.45和{}

  2. round比较abs(number-123.45)(0.006)和{}(0.004),并选择较小的一个。

  3. 所以,123.46就是结果。

如果设number123.455,则n为{}:

  1. round将得到两个数字:123.45和{}

  2. round比较abs(number-123.45)(0.005)和{}(0.005)。他们是平等的。因此round检查123.45和{}的最后一位。偶数是结果。

  3. 因此,结果是123.46

我说得对吗?在

如果不是,你能提供一个可理解的版本,值被四舍五入到10的最接近的倍数减去ndigits?在


Tags: andofthetonumberifisvalue
2条回答
ndigits = 0 => pow(10, -ndigits) = 10^(-ndigits) = 1
ndigits = 1 => pow(10, -ndigits) = 10^(-ndigits) = 0.1
etc.

>>> for ndigits in range(6):
...     print round(123.456789, ndigits) / pow(10, -ndigits)
123.0
1235.0
12346.0
123457.0
1234568.0
12345679.0

基本上,你得到的数字总是10^(-ndigits)的整数倍。对于ndigits=0,这意味着您得到的数字本身就是一个整数;对于ndigts=1,这意味着它在小数点后不会有多个非零值。在

知道任何0的幂次都等于1是有帮助的。随着ndigits的增加,函数:

当您增加ndigit时,f(ndigits) = 10-ndigits会变小。特别是当您将ndigits增加1时,只需将精度为1的小数位向左移动。e、 g.10^-0 = 110^-1 = .1和{}。答案中1的位置是round的最后一个精度点。在

上面写着

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; 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).

这在python3中有意外的行为,它将对所有float有效。考虑您给出的示例,round(123.455, 2)生成值123.45。这是预期的行为,因为10^-2的最接近的偶数倍是123.46,而不是{}!在

要理解这一点,您必须特别注意以下注释:

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.

这就是为什么某些浮动会舍入到“错误的值”,而且据我所知,确实没有简单的解决办法。(sadface)如果您希望获得不同于浮点不可预测行为的行为,可以使用分数(即表示分子和分母的两个变量)来表示自定义取整函数中的浮点值。在

相关问题 更多 >