Python 的 `decimal` 模組

Python 的 `decimal` 模組

本文介紹了 Python 的 decimal 模組。

通過本文,你可以學習使用 decimal 模組進行計算的基礎、控制精度、四捨五入等內容,並提供代碼範例。

YouTube Video

Python 的 decimal 模組

Python 的 decimal 模組提供固定精度的小數運算,以避免浮點操作中產生的誤差。通過使用此模組,可以在財務計算或需要高精度的計算中獲得更可靠的結果。在 float 類型誤差成為問題的情況下,decimal 模組是一個有效的解決方案。

decimal 模組的基本用法

使用 decimal 模組時,先導入 Decimal 類,並將值作為此類的實例進行處理。接下來,我們將演示基本用法。

1from decimal import Decimal
2
3# Basic usage example of Decimal
4a = Decimal('0.1')
5b = Decimal('0.2')
6result = a + b
7
8print(f"Result: {result}")  # Result: 0.3
  • 此代碼使用 Decimal 類準確地將 0.1 和 0.2 相加。使用 float 類型執行相同計算會導致誤差,而 Decimal 能夠避免這些誤差。

控制精度

decimal 模組允許輕鬆控制計算中的精度(小數位數)。可以使用 getcontext() 函數獲取當前上下文並修改其設置。

1from decimal import Decimal, getcontext
2
3# Set the precision
4getcontext().prec = 4  # Set to 4 decimal places
5
6a = Decimal('1') / Decimal('3')
7print(f"Result with precision 4: {a}")  # Result with precision 4: 0.3333
  • 在此範例中,計算 1 ÷ 3 的精度設置為 4 位數。通過使用 Decimal,您可以根據需要設置計算精度,從而對結果進行相應調整。

四捨五入

decimal 模組包含多種指定四捨五入方法的選項。以下是使用多種四捨五入選項的範例,例如 ROUND_UPROUND_DOWN

 1from decimal import Decimal, ROUND_UP, ROUND_DOWN
 2
 3# Example of rounding a number
 4a = Decimal('1.2345')
 5
 6# Rounding up
 7rounded_up = a.quantize(Decimal('0.01'), rounding=ROUND_UP)
 8print(f"Rounded Up: {rounded_up}")  # Rounded Up: 1.24
 9
10# Rounding down
11rounded_down = a.quantize(Decimal('0.01'), rounding=ROUND_DOWN)
12print(f"Rounded Down: {rounded_down}")  # Rounded Down: 1.23
  • 此處使用 quantize() 將數字四捨五入或向下取整至 2 位小數精度。這使得四捨五入以及其他多種方式的計算成為可能。

操作上下文及例外

decimal 模組還可以處理操作期間發生的錯誤和例外。可以為特定錯誤(如除以零或溢出)定義自訂處理方式。

1from decimal import Decimal, getcontext, DivisionByZero
2
3# Exception handling
4getcontext().traps[DivisionByZero] = True
5
6try:
7    result = Decimal('1') / Decimal('0')
8except DivisionByZero:
9    print("Division by zero error caught!")
  • 在這個例子中,當發生除以零的情況時,捕捉到 DivisionByZero 異常。在 decimal 模組中,可以以這種方式控制和自訂錯誤。

總結

decimal 模組在財務計算或需要高精度以避免浮點數錯誤的情況下非常有用。它支援廣泛的應用,從基本計算到精度管理、四捨五入和異常處理。請回顧以下總結點,並根據您的具體需求使用 decimal 模組。

  • 使用 Decimal 類可以進行精確的十進位算術運算。
  • 您可以自由調整精度和四捨五入的設定。
  • 可以管理例如除以零這樣的異常情況。

這允許您使用 decimal 模組,在需要精確數值計算的情況下將錯誤降到最低。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video