泸州市网站建设_网站建设公司_响应式开发_seo优化
2026/1/8 18:48:59 网站建设 项目流程

下面记录Python的奇怪行为

  1. round()

    系统提升的round()说明

Help on built-in function round in module builtins:

round(number, ndigits=None)
Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.

然而,并不简单 round不是简单的四舍五入,而是“银行家算法”,四舍六入五成双。

对应的C语言如下

#include <stdio.h> #include <math.h> int main() { printf("%0.3f\n",round(1.75*10)/10); printf("%0.3f\n",round(1.65*10)/10); printf("%0.3f\n",round(-1.65*10)/10); printf("%0.3f\n",round(-1.75*10)/10); return 0; }

运行结果如下:

1.800
1.700
-1.700
-1.800

嗯,正常的四舍五入。

但是,根据IEEE 754 标准,正常行为是“银行家舍入法”(Banker's Rounding)。

目的是:减少大量数据舍入时的系统性偏差。

同时,还发现以下迷思

当参数n不存在时,round()函数的输出为整数

当参数n存在时,即使为0,round()函数的输出也会是一个浮点数

>>> type(round(5.7))
<class 'int'>
>>> type(round(5.7,0))
<class 'float'>
>>> type(round(5.7,1))
<class 'float'>

也是醉了

本文会不定期增加内容。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询