python的小數(shù)數(shù)字對象,類似于浮點(diǎn)數(shù),只不過小數(shù)數(shù)字有固定的位數(shù)和小數(shù)點(diǎn)。
python小數(shù)數(shù)字是有固定精度的浮點(diǎn)值。
python小數(shù)數(shù)字對象的性能略微低于浮點(diǎn)數(shù)。
python小數(shù)數(shù)字需使用decimal模塊。
python的decimal.getcontext().prec可以設(shè)置小數(shù)精度。
1.1 python小數(shù)基礎(chǔ)知識(shí)
python浮點(diǎn)數(shù)缺乏精確性,因?yàn)榇鎯?chǔ)數(shù)值的空間有限。
python小數(shù)對象可以修正浮點(diǎn)數(shù)的精確性問題。
1.1.1 Decimal()
python不同小數(shù)位數(shù)的Decimal對象運(yùn)算時(shí),自動(dòng)升級(jí)為小數(shù)位數(shù)最多的小數(shù)位。
用法
Decimal(str)
描述
生成小數(shù)字符串對應(yīng)的Decimal對象。
入?yún)?/strong>
str:小數(shù)字符串
示例
>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> print(0.1+0.1+0.1-0.3)
5.551115123125783e-17
>>> from decimal import Decimal
>>> Decimal('0.1')+Decimal('0.1')+Decimal('0.1')-Decimal('0.3')
Decimal('0.0')
>>> Decimal('0.10')+Decimal('0.1')+Decimal('0.1')-Decimal('0.3')
Decimal('0.00')
1.2 設(shè)置全局精度
python通過上下文對象(decimal.getcontext().prec)設(shè)置小數(shù)的全局精度。
示例
>>> import decimal
>>> decimal.Decimal(1)/decimal.Decimal(7)
Decimal('0.1428571428571428571428571429')
>>> decimal.getcontext().prec = 4
>>> decimal.Decimal(1)/decimal.Decimal(7)
Decimal('0.1429')
1.3 臨時(shí)設(shè)置精度
python通過本地上下文管理器(decimal. localcontext ().prec)設(shè)置小數(shù)的臨時(shí)精度。語句執(zhí)行完后,繼續(xù)使用初始精度。
示例
>>> import decimal
>>> decimal.Decimal('1.00')/decimal.Decimal('3.00')
Decimal('0.3333333333333333333333333333')
>>> with decimal.localcontext() as ctx:
... ctx.prec = 2
... decimal.Decimal('1.00')/decimal.Decimal('3.00')
...
...
Decimal('0.33')
>>> decimal.Decimal('1.00')/decimal.Decimal('3.00')
Decimal('0.3333333333333333333333333333')
-
浮點(diǎn)數(shù)
+關(guān)注
關(guān)注
0文章
61瀏覽量
16054 -
python
+關(guān)注
關(guān)注
56文章
4822瀏覽量
85900
發(fā)布評(píng)論請先 登錄
Python的面向對象編程詳解

VHDL 怎么定義整數(shù)數(shù)組和小數(shù)數(shù)組啊
Python中常用的數(shù)據(jù)類型
3分鐘看懂Python面向對象
總結(jié):一文了解Python中的數(shù)字類型
詳談Python的數(shù)據(jù)模型和對象模型

python二八十六進(jìn)制整數(shù)轉(zhuǎn)換
Python中的類和對象詳解
使用Teachable Machine和Python輕松進(jìn)行對象檢測

評(píng)論