精確的小數 decimal高階

2021-08-21 05:16:28 字數 2649 閱讀 4751

原載於

用科學計數法的方式來表示小數的話,指數最大值是多少?超過了能表示的最大數值的話會如何?

在運算的時候可能產生除以零的錯誤;和乙個無效的數值進行計算,比如說有些數值用'-'和'na'來表示的,跟它們進行計算會產生哪種錯誤提示?

>>> from decimal import *

>>> getcontext()

context(prec=28, rounding=round_half_even, emin=-999999999, emax=999999999, capitals=1, flags=, traps=[invalidoperation, overflow, divisionbyzero])

>>> c=getcontext()

>>> c.prec=2

>>> c.emax=2

>>> c

context(prec=2, rounding=round_half_even, emin=-999999999, emax=2, capitals=1, flags=, traps=[invalidoperation, overflow, divisionbyzero])

>>> decimal('99999')

decimal('99999')

>>> decimal('99999')+1

traceback (most recent call last):

file "", line 1, in file "/library/frameworks/python.framework/versions/2.7/lib/python2.7/decimal.py", line 1209, in __add__

ans = ans._fix(context)

file "/library/frameworks/python.framework/versions/2.7/lib/python2.7/decimal.py", line 1676, in _fix

ans = context._raise_error(overflow, 'above emax', self._sign)

file "/library/frameworks/python.framework/versions/2.7/lib/python2.7/decimal.py", line 3872, in _raise_error

raise error(explanation)

decimal.overflow: above emax

>>> getcontext().create_decimal('99999')

traceback (most recent call last):

file "", line 1, in file "/library/frameworks/python.framework/versions/2.7/lib/python2.7/decimal.py", line 3937, in create_decimal

return d._fix(self)

file "/library/frameworks/python.framework/versions/2.7/lib/python2.7/decimal.py", line 1676, in _fix

ans = context._raise_error(overflow, 'above emax', self._sign)

file "/library/frameworks/python.framework/versions/2.7/lib/python2.7/decimal.py", line 3872, in _raise_error

raise error(explanation)

decimal.overflow: above emax

>>> decimal('99')+decimal('0.1')

decimal('99')

>>> getcontext()

context(prec=2, rounding=round_half_even, emin=-999999999, emax=2, capitals=1, flags=[rounded, inexact, overflow], traps=[invalidoperation, overflow, divisionbyzero])

round_floor

round_half_down

round_half_even

round_half_up

round_up

round_down

round_05up

>>> getcontext()

context(prec=2, rounding=round_half_even, emin=-999999999, emax=2,

capitals=1, flags=[rounded, inexact, overflow],

traps=[invalidoperation, overflow, divisionbyzero])

python執行精確的小數計算

在進行浮點數計算時它們無法精確表達出所有的十進位製小數字。a 4.1 b 5.329 print a b 9.428999999999998這些誤差實際上是底層cpu的浮點運算單元和ieee754浮點數算數標準的一種 特性 python的浮點數型別儲存的資料採用的是原始表示形式,因此使用float例...

精確到小數點位數的方法

1.在c語言中 可以直接 1f 中間這個數字就代表了要保留的小數點位數。include intmain 2.在c 中 常常採用的方法 需要用到頭檔案和函式setprecision n 括號中的n表示要精確的位數。包含標頭檔案 include 語句示例 cout include include usi...

js精確到指定位數的小數

將數字四捨五入到指定的小數字數。使用math.round 和模板字面量將數字四捨五入為指定的小數字數。省略第二個引數decimals,數字將被四捨五入到乙個整數。const round n,decimals 0 number e e round 3.1415926535897932384626433...