Python round() 函数及示例

Round()

Round() 是 Python 中内置的函数。它会返回一个根据你输入的精度进行四舍五入后的浮点数。

如果未指定四舍五入的小数位数,则默认为 0,并四舍五入到最接近的整数。

语法

round(float_num, num_of_decimals)

参数

  • float_num:要四舍五入的浮点数。
  • num_of_decimals:(可选)四舍五入时要考虑的小数位数。此参数是可选的,如果未指定,则默认为 0,并将四舍五入到最接近的整数。

描述

round() 方法接受两个参数:

  • 要四舍五入的数字,以及
  • 四舍五入时应考虑的小数位数。

第二个参数是可选的,在未指定时默认为 0,此时将四舍五入到最接近的整数,返回类型也将是整数。

当指定了小数位数(即第二个参数)时,它将四舍五入到指定的小数位数。返回类型将是浮点数。

如果指定的小数位之后

  • 大于等于 5,则在最终值上加 1
  • 小于 5,则最终值将保持不变,直到指定的小数位数。

返回值

如果未给出 num_of_decimals,则返回整数值;如果给出了 num_of_decimals,则返回浮点数值。请注意,如果小数点后的值大于等于 5,则值将四舍五入到 +1,否则将返回直到指定小数位的值。

四舍五入会产生多大的影响?(四舍五入 vs 截断)

说明四舍五入影响的最佳例子是股票交易所。在过去,即 1982 年,温哥华证券交易所(VSE)在每次交易时会将股票价格截断到小数点后三位。

每天大约进行 3000 次这样的操作。累积的截断导致每月损失约 25 点。

下面展示了截断值与四舍五入值的对比示例。

以下是下面生成的浮点数,用作股票价格。目前我生成的是介于 0.01 和 0.05 之间的

1,000,000 秒的数据。

示例

arr = [random.uniform(0.01, 0.05) for _ in range(1000000)]

为了展示四舍五入的影响,我编写了一个小程序,首先,您只需要使用小数点后三位数字,即截断小数点后三位之后的数字。

我列出了原始总值、截断值总计以及原始值与截断值之间的差异。

对于同一组数字,我使用了 round() 方法处理小数点后三位,并计算了原始值与四舍五入值之间的总和和差值。

以下是示例和输出:
示例 1

import random

def truncate(num):
    return int(num * 1000) / 1000

arr = [random.uniform(0.01, 0.05) for _ in range(1000000)]
sum_num = 0
sum_truncate = 0
for i in arr:
    sum_num = sum_num + i        
    sum_truncate = truncate(sum_truncate + i)
    
print("Testing by using truncating upto 3 decimal places")
print("The original sum is = ", sum_num)
print("The total using truncate = ", sum_truncate)
print("The difference from original - truncate = ", sum_num - sum_truncate)

print("\n\n")
print("Testing by using round() upto 3 decimal places")
sum_num1 = 0
sum_truncate1 = 0
for i in arr:
    sum_num1 = sum_num1 + i        
    sum_truncate1 = round(sum_truncate1 + i, 3)


print("The original sum is =", sum_num1)
print("The total using round = ", sum_truncate1)
print("The difference from original - round =", sum_num1 - sum_truncate1)

输出

Testing by using truncating upto 3 decimal places
The original sum is =  29985.958619386867
The total using truncate =  29486.057
The difference from original - truncate =  499.9016193868665



Testing by using round() up to 3 decimal places
The original sum is = 29985.958619386867
The total using round =  29985.912
The difference from original - round = 0.04661938686695066

原始值与截断后的差异为 499.9016193868665,而四舍五入后的差异为 0.04661938686695066。

差异看起来很大,这个例子展示了 round() 方法如何帮助我们获得更接近的准确值。

示例:四舍五入浮点数

在此程序中,我们将看到四舍五入在浮点数上的工作原理。

# testing round() 

float_num1 = 10.60 # here the value will be rounded to 11 as after the decimal point the number is 6 that is >5 

float_num2 = 10.40 # here the value will be rounded to 10 as after the decimal point the number is 4 that is <=5

float_num3 = 10.3456 # here the value will be 10.35 as after the 2 decimal points the value >=5 

float_num4 = 10.3445 #here the value will be 10.34 as after the 2 decimal points the value is <5 

print("The rounded value without num_of_decimals is :", round(float_num1))
print("The rounded value without num_of_decimals is :", round(float_num2))
print("The rounded value with num_of_decimals as 2 is :", round(float_num3, 2))
print("The rounded value with num_of_decimals as 2 is :", round(float_num4, 2))

输出

The rounded value without num_of_decimals is : 11
The rounded value without num_of_decimals is : 10
The rounded value with num_of_decimals as 2 is : 10.35
The rounded value with num_of_decimals as 2 is : 10.34

示例:四舍五入整数

如果您对整数值使用 round(),它将原样返回该数字,没有任何更改。

# testing round() on a integer

num = 15

print("The output is", round(num))

输出

The output is 15

示例:对负数进行四舍五入

让我们来看一些关于四舍五入如何处理负数的示例。

# testing round()

num = -2.8
num1 = -1.5
print("The value after rounding is", round(num))
print("The value after rounding is", round(num1))

输出

C:\pythontest>python testround.py
The value after rounding is -3
The value after rounding is -2

示例:四舍五入 NumPy 数组

如何在 Python 中四舍五入 NumPy 数组

为了解决这个问题,我们可以使用 numpy 模块并使用 numpy.round() 或 numpy.around() 方法,如下面的示例所示。

使用 numpy.round()

# testing round()
import numpy as np

arr = [-0.341111, 1.455098989, 4.232323, -0.3432326, 7.626632, 5.122323]

arr1 = np.round(arr, 2)

print(arr1)

输出

C:\pythontest>python testround.py
[-0.34  1.46  4.23 -0.34  7.63  5.12]

我们还可以使用 numpy.around(),它会给出与下面示例相同的结果。

示例:Decimal 模块

除了 round() 函数,Python 还有一个 decimal 模块,可以帮助更准确地处理十进制数。

Decimal 模块提供了舍入类型,如下所示:

  • ROUND_CEILING:向正无穷方向四舍五入;
  • ROUND_DOWN:向零方向舍入;
  • ROUND_FLOOR:向负无穷方向四舍五入;
  • ROUND_HALF_DOWN:四舍五入到最接近的数,但朝向零;
  • ROUND_HALF_EVEN:四舍五入到最接近的数,当出现.5 时,朝向最接近的偶数整数;
  • ROUND_HALF_UP:四舍五入到最接近的数,但远离零;
  • ROUND_UP:当值远离零时进行四舍五入。

在 decimal 中,quantize() 方法有助于将数字四舍五入到固定的小数位数,您可以指定要使用的舍入方式,如下面的示例所示。
示例
使用 round() 和 decimal 方法

import  decimal 
round_num = 15.456

final_val = round(round_num, 2)

#Using decimal module
final_val1 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_CEILING)
final_val2 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_DOWN)
final_val3 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_FLOOR)
final_val4 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_DOWN)
final_val5 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_EVEN)
final_val6 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)
final_val7 = decimal.Decimal(round_num).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP)

print("Using round()", final_val)
print("Using Decimal - ROUND_CEILING ",final_val1)
print("Using Decimal - ROUND_DOWN ",final_val2)
print("Using Decimal - ROUND_FLOOR ",final_val3)
print("Using Decimal - ROUND_HALF_DOWN ",final_val4)
print("Using Decimal - ROUND_HALF_EVEN ",final_val5)
print("Using Decimal - ROUND_HALF_UP ",final_val6)
print("Using Decimal - ROUND_UP ",final_val7)

输出

Using round() 15.46
Using Decimal - ROUND_CEILING  15.46
Using Decimal - ROUND_DOWN  15.45
Using Decimal - ROUND_FLOOR  15.45
Using Decimal - ROUND_HALF_DOWN  15.46
Using Decimal - ROUND_HALF_EVEN  15.46
Using Decimal - ROUND_HALF_UP  15.46
Using Decimal - ROUND_UP  15.46

摘要

  • Round(float_num, Num_of_decimals) 是 Python 中内置的函数。它将返回一个根据您输入的精度进行四舍五入的浮点数。
  • float_num:要四舍五入的浮点数。
  • Num_of_decimals:四舍五入时要考虑的小数位数。
  • 如果未给出 num_of_decimals,则返回整数值;如果给出了 num_of_decimals,则返回浮点数值。