跳至主要内容

How to Round Up a Number in Python

了解在 Python 中向上取整的三种直接方法:使用 math 模块中的 math.ceil()、使用 decimal 模块,以及使用 NumPy。
· 7分钟 阅读

使用 AI 探索

作为一门极其灵活的编程语言,Python 提供了多种向上取整以及更一般四舍五入的技巧。向上取整是必须掌握的编程技巧,尤其适用于从事金融或统计工作的人。以下方法在许多实际应用中大同小异,但也存在一些细微且关键的差异。本文将向您展示多种向上取整的方法,并在最后讨论它们之间的不同之处。

如果您正立志成为数据分析师或数据科学家,强烈推荐学习 DataCamp 的Introduction to Python课程,抢先一步掌握 Python 编程。Python 初学者速查表也同样是非常实用的参考资料。

快速答案:如何在 Python 中向上取整

math 模块中的 math.ceil() 函数提供了一个简单的方法来将数字向上取整。该方法可确保结果总是被进位到比原值更大的下一个整数。下面的代码会打印出 4。

# Import the math module to access math.ceil() function
import math
number = 3.14
rounded_up = math.ceil(number)
print(rounded_up)

理解向上取整的基础

对数字进行四舍五入,是通过调整数位来给出近似值。这一概念对于简化数字、便于处理至关重要。向上取整的常见用例如下:

  • 财务计算:向上取整常用于财务计算,以确保保守估计。例如,在计算利率或税费时,向上取整到最接近的分可以避免低估数值。
  • 数据分析与统计:很多数据报告在标注置信区间、报告 p 值等方面遵循特定的规范,因为不必要的高精度会分散注意力。
  • 编码与算法:取整函数可用于控制计算精度,这对性能以及避免浮点误差都至关重要。

需要牢记的是,如果在执行计算之前就对数字进行取整,您将改变结果,而且有时这种变化可能比预期更显著或更令人意外。由于向上取整会将数字调整为近似值,误差会累积,尤其是在处理大型数据集时。如果在相乘前对所有数字都向上取整,结果很可能会高于直接使用原始数字的结果。这是因为每个数值略微变大,会推高整体乘积。

另一方面,如果在进行除法前统一向上取整,其影响会因被除数或除数被取整而不同。无论哪种情况,在进行数学运算前先向上取整,都可能以出乎意料的方式影响结果,如果不加留意就更是如此。

在 Python 中向上取整的方法

Python 通过 math 模块、NumPy 和 Pandas 等库,提供了多种向上取整的方法。

使用 math 模块向上取整

math 中的 math.ceil() 函数用于将数字向上取整到最接近的整数。语法如下所示。

# Import the math module to access math.ceil() function
import math
math.ceil(number)

当使用 math.ceil() 对正数进行向上取整时,输出会返回一个大于原数值的整数。下面的代码会打印 4。

# Import the math module to access math.ceil() function
import math
number = 3.14
rounded_up = math.ceil(number)
print(rounded_up)

同样地,对负数进行向上取整时,math.ceil() 会返回一个比原值更大的(即更接近正无穷的)负整数。下面的代码会打印 -3。

# Import the math module to access math.ceil() function
import math
number = -3.14
rounded_up = math.ceil(number)
print(rounded_up)

使用 decimal 模块获得精确取整

Python 的 decimal 模块适用于将浮点数精确到特定小数位,尤其在金融计算中实现精确的小数取整非常重要。

您可以使用 decimal 模块从字符串、整数以及浮点数创建 Decimal 对象。但由于潜在的精度问题,不推荐用浮点数来创建 Decimal 对象。下面的示例展示了创建 Decimal 对象的不同方法。

# Import the decimal module to access Decimal function
from decimal import Decimal
d1 = Decimal("3.14159")
print(d1)
# Import the decimal module to access Decimal function
from decimal import Decimal
d3 = Decimal(3.14159)
print(d3)

decimal 模块提供了以下用于向上取整的方式:

  • ROUND_UP:始终远离 0 进行进位取整。

  • ROUND_CEILING:始终向正无穷方向取整。

使用 decimal 模块,您可以通过 .quantize() 方法将数字取整到所需精度。下面的示例中,我们使用 ROUND_UP 方法将小数向远离 0 的方向取整到最近的整数。通过在 Decimal 中指明 1,即可表示取整到整数位。

# Import the Decimal class and the ROUND_UP rounding mode from the decimal module
from decimal import Decimal, ROUND_UP

# Create a Decimal object from a string representation of a floating-point number
d = Decimal("-3.14159")

# Round the Decimal object to nearest integer using the ROUND_UP rounding mode
rounded_d_int = d.quantize(Decimal("1"), rounding=ROUND_UP)
print(rounded_d_int) # prints -4

Decimal 模块中的 ROUND_CEILING 方式同样可以将数字向上取整到更大的整数。

# Import the Decimal class and the ROUND_CEILING rounding mode from the decimal module
from decimal import Decimal, ROUND_CEILING

# Create a Decimal object from a string representation of a floating-point number
d = Decimal("-3.14159")

# Round the Decimal object to nearest integer using ROUND_CEILING rounding mode
rounded_d_int = d.quantize(Decimal("1"), rounding=ROUND_CEILING)
print(rounded_d_int) # prints -3

使用 NumPy 对数组向上取整

NumPy 是 Python 中功能强大的库,可用于对大型数组和矩阵进行运算。由于其高效与便捷,在数据科学中不可或缺。NumPy 也提供了对数字进行向上取整的操作。下面我们来看 np.ceil() 方法,它可以将数组中的各元素向上取整到最近的整数。np.ceil() 的语法十分直观,如下所示。

np.ceil(array)

下面的示例展示了如何使用 np.ceil() 对数组中的元素进行向上取整。

# Import the numpy module and alias it as np for convenience
import numpy as np

# Create a numpy array with floating-point numbers
array = np.array([3.14, 2.72, 1.61])

# Apply the ceiling function to each element in the numpy array, rounding each number up to the nearest integer
rounded_up_array = np.ceil(array)
print(rounded_up_array) # 4, 3, 2

总结对比

下面是一张对比表,总结了在 Python 中进行向上取整的不同方法:

方法优点缺点最佳用例
math 模块通过 math.ceil() 提供明确的向上取整选项需要引入 math 模块,不适用于复杂的取整场景。涉及特定取整(包括向上取整)的计算。
decimal 模块高精度与高准确性使用较为复杂金融计算
NumPy使用 np.ceil() 高效处理数组取整需要安装 NumPy 库对大型数据集进行数据分析。

处理取整偏差

取整偏差是指在使用取整方法时引入的数值失真。它通常发生在数字被调整为比原值更大或更小的近似值时。因此,取整偏差会降低精度和准确性,尤其是在统计分析和财务计算中。

四舍五入(half up)

“四舍五入(half up)”方法指当一个数恰好位于两个可能值的中间时,向上取整。例如,2.5 会被取整为 3。该方法的优点是易于理解,并与学校中最常教授的规则一致。下面的代码中,我们创建了一个函数来检查小数部分是否恰好为 0.5,是则进位,否则舍去。

# Create a function to check if a decimal is exactly 0.5 and round up if true
def round_half_up(n):
    if n - int(n) == 0.5:
        return int(n) + 1
    return round(n)
# Example usage
example_number = 2.5
rounded_number = round_half_up(example_number)
print(rounded_number)

“四舍六入五留双”(银行家舍入法)

“四舍六入五留双”(round half to even),又称银行家舍入法,是用于最小化偏差的一种取整方式。当一个数恰好位于两个整数之间时,将其取整为最接近的偶数。这种方法有助于平衡取整过程,避免持续的上偏或下偏。

如果省略第二个参数,内置的 round 方法默认采用“舍入到偶数”的规则。

# Python round() method to round half to even
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(-2.5)) # -2

结论

在编程中,对数字进行向上取整是一项重要技巧,它让数值处理更为便捷。在统计分析和财务计算中,向上取整也同样关键,能够简化数值、提升可读性和可解释性。了解不同的取整方法,并根据具体任务需求选择合适的方法,至关重要。

作为数据分析师,建议您多练习不同的向上取整方法,理解它们在各类任务中的实际用法。推荐尝试 DataCamp 的Python Fundamentals与Python Programming技能路径以提升编程能力。最后,Python Developer职业路径将帮助您掌握进阶的 Python 技能,在众多开发者中脱颖而出。若您对 Python 中整数的内部机制感到好奇,不妨阅读我们的教程:Python 的最大整数。

Allan Ouko

作者

Allan Ouko

数据科学技术写作者,具备数据分析、商业智能和数据科学的一线实践经验。我撰写以行业为导向的实用内容,涵盖 SQL、Python、Power BI、Databricks 和数据工程,并以真实的分析工作为基础。我的写作兼顾技术深度与业务影响,帮助专业人士将数据转化为自信的决策。

Frequently Asked Questions

How do you round up to nearest int in Python?

您可以使用 math 模块中的 math.ceil() 函数在 Python 中向上取整到最接近的 int。

What is rounding bias?

取整偏差是指在取整过程中由于数字被扭曲而导致的不准确数值。

What is round half to even?

“五留双”(round half to even),也称银行家舍入法,当一个数恰位于两个整数之间时,将其取整为最接近的偶数。

What is the difference between rounding and truncating?

取整是根据小数部分的数值对数字进行调整;截断则是不进行取整,直接去掉数字的小数部分。

What if I want to round down instead of rounding up in Python?

如果您希望在 Python 中向下取整而不是向上取整,可以使用 math.floor() 函数。math.ceil() 会将数字向上取整到最近的整数,而 math.floor() 则会将数字向下取整到最近的整数。

主题