您必须使用1000个十进制数字设置上下文:
context = decimal.Context(prec=1000)decimal.setcontext(context)
从现在开始,计算将使用1000位精度。
例:
>>> decimal.setcontext(decimal.Context(prec=1000))>>> pi = decimal.Decimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113')>>> piDecimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113')>>> pi + 2Decimal('5.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113')注意:
- 您必须使用字符串来初始化,
Decimal
因为如果使用float
,解释器将必须首先截断它。(我也相信,只有最新版本的decimal
accept才可以接受float
参数。在旧版本中,您必须Decimal.from_float
改用它)。 - 在计算过程中保留十进制数字。
您还可以通过
localcontextcontextmanager在本地使用上下文:
context = decimal.Context(prec=1000)with decimal.localcontext(context): # here decimal uses 1000 digits for computations pass# here the default context is restored.



