5

python 中的小数舍入方法

 2 years ago
source link: https://xujinzh.github.io/2022/05/17/python-round/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

数学中,四舍五入是我们经常使用的,用来对小数保留有效位精度,得到近似值,节省书写,如 3.141592653589793…≈3.14,这同样也方便记忆一些无理数的近似值,当计算时也比较方便。但除了四舍五入,还存在一些其他的小数舍入方法,如“四舍六入五成双”等。Python 中内置的 round 函数采用哪种舍入方法呢?

四舍五入是我们小学时就学习的一种小数舍入方法。如

3.141592653589793...

保留 3 位小数,则为

3.142

因为,第 4 位是数值 5,根据四舍五入原则(小于等于 4 的舍去,大于等于 5 的舍入进 1),因此,进行舍入进 1.

四舍六入五成双

四舍六入五成双和四舍五入的区别就是,当舍入位后没有数值,且舍入位是 5 时,需要根据舍入位前面一位的数值奇偶性进行舍入。

基本原则是:

  1. 当舍入位小于等于 4 时,舍去;
  2. 当舍入位大于等于 6 时,舍入进 1;
  3. 当舍入位等于 5 时,分两种情况:1)舍入位 5 后面有数值,则舍入进 1;2)舍入位 5 后面没有数值,看舍入位 5 前面的数值,当其是奇数时,舍入进 1,当其是偶数时,舍去。这样在该种情况下得到的近似数末尾值肯定时偶数。

如,保留下面小数的 3 位有效数字:

3.1415

四舍六入五成双后

3.142

如,保留下面小数的 7 位有效数字:

3.14159265

四舍六入五成双后

3.1415926

python round

python 中内置的小数舍入方法是 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). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number.

它和上面的四舍五入和四舍六入五成双都不同,具体例子表现为:

round(3.125, 2)
3.12
round(3.135, 2)
3.13
round(3.136, 2)
3.14
round(2.45, 1)
2.5
round(2.675, 2)
2.67
round(2.665, 2)
2.67
round(2.685, 2)
2.69
round(1.5)
2
round(2.5)
2
round(1.2000, 3)
1.2

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK