江蘇鹽城網(wǎng)站建設(shè)優(yōu)化網(wǎng)站建設(shè)
Python decimal 模塊
Python中的浮點數(shù)默認(rèn)精度是15位。
Decimal對象可以表示任意精度的浮點數(shù)。
getcontext函數(shù)
用于獲取當(dāng)前的context環(huán)境,可以設(shè)置精度、舍入模式等參數(shù)。
#在context中設(shè)置小數(shù)的精度
decimal.getcontext().prec = 100
通過字符串初始化Decimal類型的變量
因為通過浮點數(shù)初始化Decimal類型的變量會導(dǎo)致精度的丟失
# 浮點數(shù)的初始化
a = decimal.Decimal('3.14159265')
setcontext函數(shù)
decimal.ROUND_HALF_UP 對浮點數(shù)四舍五入
import decimal
x = decimal.Decimal('1.23456789')
context = decimal.Context(prec=4,rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(context)
y1 = x
y2 = x*2
print("y1",y1)
print("y2",y2)>>>y1 1.23456789
>>>y2 2.469
localcontext函數(shù)
用于創(chuàng)建一個新的context環(huán)境,可以在該環(huán)境中設(shè)置精度、舍入模式等參數(shù),不會影響全局的context環(huán)境。
import decimal
x = decimal.Decimal('1.23456789')
context0 = decimal.Context(prec=9,rounding=decimal.ROUND_HALF_UP)
decimal.setcontext(context0)
y1 = x * 2
print("y1",y1)with decimal.localcontext() as context:context.prec = 4context.rounding = decimal.ROUND_HALF_UPy2 = x * 2print("y2",y2)>>>y1 2.46913578
>>>y2 2.469
>>>
>>>