如何使用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中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

asyncio.Queue是用於異步任務間安全通信的隊列工具,1.生產者通過awaitqueue.put(item)添加數據,消費者用awaitqueue.get()獲取數據;2.每處理完一項需調用queue.task_done(),以便queue.join()等待所有任務完成;3.使用None作為結束信號通知消費者停止;4.多個消費者時,需發送多個結束信號或在取消任務前確保所有任務已處理完畢;5.隊列支持設置maxsize限制容量,put和get操作自動掛起不阻塞事件循環,程序最終通過canc

正則表達式在Python中通過re模塊實現,用於搜索、匹配和操作字符串。 1.使用re.search()在整個字符串中查找第一個匹配項,re.match()僅在字符串開頭匹配;2.用括號()捕獲匹配的子組,可命名以提高可讀性;3.re.findall()返回所有非重疊匹配的列表,re.finditer()返回匹配對象的迭代器;4.re.sub()替換匹配的文本,支持函數動態替換;5.常用模式包括\d、\w、\s等,可使用re.IGNORECASE、re.MULTILINE、re.DOTALL、re

要調試遠程Python應用,需使用debugpy並配置端口轉發和路徑映射:首先在遠程機器安裝debugpy並修改代碼以監聽5678端口,通過SSH隧道將遠程端口轉發到本地,然後在VSCode的launch.json中配置“AttachtoRemotePython”並正確設置localRoot和remoteRoot路徑映射,最後啟動應用並連接調試器,即可實現遠程斷點調試、變量檢查和代碼步進,整個過程依賴debugpy、安全的端口轉發及精確的路徑匹配完成。

確保pytythonisinstalledbyrunningpypython-versionorpython3-- versionIntheterminal; ifnotinStalled,下載frompython.organdaddtopath.2.insublimetext,gototools> buildSystem> buildsystem> buildsystem> newbuildsystem

要運行Python腳本,需配置SublimeText的構建系統:1.確保已安裝Python並可在命令行使用;2.在SublimeText中創建新構建系統,輸入{"cmd":["python","-u","$file"],"file_regex":"^[]File\"(...?)\",line([0-9]*)","selector":&qu

InstallandconfigureLSPwithaPythonlanguageserverlikepylspforIDE-likefeaturessuchassaferename,findreferences,andgotodefinition.2.UseSublimeText’sFindinFileswithwholewordandregexoptionsforcarefulmanualrefactoringacrossfiles.3.Integrateexternaltoolsliker

要找到兩個或多個列表的公共元素,最有效的方法是使用集合的交集操作。 1.將列表轉換為集合,並使用&運算符或.intersection()方法求交集,例如common=list(set(list1)&set(list2));2.對於多個列表,可使用set(list1).intersection(set(list2),set(list3))或set.intersection(*map(set,lists))實現動態處理;3.注意結果無序且自動去重,若需保持順序,可遍歷原列表並結合集合判
