首頁  >  文章  >  後端開發  >  如何使用Python進行準確的小數計算?

如何使用Python進行準確的小數計算?

WBOY
WBOY轉載
2023-08-23 15:53:082367瀏覽

如何使用Python進行準確的小數計算?

在本文中,我們將學習如何在Python中進行準確的十進位計算。

使用的方法

  • Using the Decimal() function of the decimal Module

  • #使用math模組的fsum()函數

浮點數無法準確表示所有十進制數是眾所周知的缺點。此外,即使是簡單的數學計算也會產生一些錯誤。例如 −

Example

以下程式展示了浮點整數無法準確表示所有十進制數的能力-

x = 4.2
y = 3.1
 
# printing the sum of both the variables
print("x + y =", x + y)
 
# checking if the sum is both the variables is equal to 7.3
print((x + y) == 7.3)

輸出

執行時,上述程式將產生以下輸出 -

x + y = 7.300000000000001
False

這些誤差是系統底層的CPU和其浮點數單元所使用的IEEE 754算術標準的「特性」。如果您使用float實例編寫程式碼,那麼無論如何都無法防止此類錯誤,因為Python的float資料類型使用本機表示來保存資料。

Using the decimal module will give you greater accuracy at the cost of some performance. Let us see it below.

方法一:使用decimal模組的Decimal()函式

Example

以下程式展示了使用Decimal()函數進行精確的十進制計算的範例:

# importing Decimal from decimal module
from decimal import Decimal
x = Decimal('4.2')
y = Decimal('3.1')
# printing the sum of both the variables
print("x + y =", x + y)
# checking if the sum is both the variables is equal to 7.3 using by passing the sum to the Decimal Function
print((x + y) == Decimal('7.3'))

輸出

執行時,上述程式將產生以下輸出 -

x + y = 7.3
True

在上述程式碼中,一開始可能會感覺有點奇怪,即將數字指定為字串。然而,十進位物件的工作方式與您希望的完全相同(支援所有常見的數學運算等)。當您列印它們或在字串格式化函數中使用它們時,它們看起來就像普通的數字。

控制計算的多個方面,如數字的位數和舍入方式,是decimal的關鍵特性。

Example

要執行此操作,請建立一個本機上下文並修改其設定。

# importing localcontext from decimal module
from decimal import localcontext
x = Decimal('2.3')
y = Decimal('2.7')
# dividing x by y(returns as a floating-point number)
print(x / y)
with localcontext() as context:
   # rounding the number upto 3 digits i.e, precision 3
   context.prec = 3
   # Dividing x by y with precision set to 3
   print(x / y)

輸出

執行時,上述程式將產生以下輸出 -

0.8518518518518518518518518519
0.852

將精確度值增加到'60'以獲得更高的準確度

Example

# importing localcontext from decimal module
import decimal
from decimal import localcontext
x = decimal.Decimal('2.3')
y = decimal.Decimal('2.7')
# dividing x by y(returns as a floating-point number)
print(x / y)
with localcontext() as context:
   # Rounding the number upto 60 digits i.e, precision 60
   context.prec = 60
   # Dividing x by y with precision set to 3
   print(x / y)

輸出

執行時,上述程式將產生以下輸出 -

0.8518518518518518518518518519
0.851851851851851851851851851851851851851851851851851851851852

方法2:使用math模組的fsum()函數

十進位模組實現了IBM的「通用十進制算術規範」。

不用說,有很多超出本文範圍的自訂選擇。

Python初學者可能會被誘導使用decimal模組來解決浮點資料類型的精確度問題。但也需要了解你的應用領域。在處理科學或工程問題、電腦圖形或其他科學性質的事物時,通常更常用普通浮點數類型。

例如,實際世界中很少有元素能夠以浮點數提供的17位元精度進行測量。因此,即使是微小的計算誤差也沒有影響。而且,原生浮點數的速度也明顯更快,這對於需要執行大量運算的情況至關重要。

Example

然而,你無法完全避免錯誤。許多演算法已經被數學家廣泛研究,其中一些在處理錯誤方面比其他演算法更好。此外,由於減法抵銷和加法大數和小數的做法可能導致一些後果,需要一些謹慎。

inputList = [1.23e+18, 1, -1.23e+18]

# observe how the 1 disappears here if we perform sum() on the list
print(sum(inputList)) 

輸出

執行時,上述程式將產生以下輸出−

#
0.0

fsum()函數用於在給定範圍或可迭代物件之間找到總和。它需要導入math庫。它在數學計算中被廣泛使用。

文法

下面是函數的語法。

maths.fsum( iterable )

可迭代物件可以是範圍、陣列或列表。

傳回類型 -

#它傳回一個浮點數。

Example

下面的範例可以用於在 math.fsum() 中進行更準確的實作 -

# importing math module 
import math
# input list
inputList = [1.23e+18, 1, -1.23e+18]
# adding the sum of elements of the list using the fsum() function
print(math.fsum(inputList))

輸出

執行時,上述程式將產生以下輸出 -

1.0

相較之下,你其實需要研究並理解其他演算法的誤差傳播特性。

儘管如此,處理金融等主題的程序是最常使用十進制模組的地方。當這些系統的計算中出現微小的不準確性時,這是非常令人不愉快的。

因此,decimal模組提供了一種避免這種情況的方法。當Python與資料庫互動時,經常會再次遇到Decimal對象,特別是在存取金融資料時。

結論

我們在本文中了解到,在特定情況下,常規計算會失敗,所以我們需要正確的小數計算。我們學習如何使用兩個獨立的函數decimal()和fsum()進行精確的小數計算。我們也學習如何使用localcontext()函數來設定結果的精確度。

以上是如何使用Python進行準確的小數計算?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除