看板 Python 關於我們 聯絡資訊
python內建型別decimal看說明最多可以存到小數後17位, 測試過,十七位後的數字都會是亂數 在這樣的情況下該怎麼取得17位以後的精確數字呢? 我使用的實驗數字是 Decimal(156/283) 計算機算的答案: 0.55123674911660777385 python的答案: 0.55123674911660780484 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.105.26.14 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1518321196.A.2BE.html
Sunal: Decimal(156) / Decimal(283) 02/11 12:16
Sunal: Decimal('0.5512367491166077738515901060') 02/11 12:16
Sunal: 小數後17位是計算機float 的限制 02/11 12:17
seLain: 試試看用 getcontext().prec = 42 指定 precision ? 02/11 12:17
Sunal: the decimal module has a user alterable precision (defa 02/11 12:18
Sunal: ulting to 28 places) 02/11 12:18
Sunal: getcontext().prec = 42 02/11 12:19
kenduest: 是要這樣用 Decimal(156) / Decimal(283) 02/11 12:19
kenduest: 啊,真快,推文時候已經前面有人回了 02/11 12:19
Sunal: 其實文件都有..XD (看文件是個好習慣) 02/11 12:21
感謝大家,已經順利解答。我也是看這份文件一知半解, 的確應該不能在Decimal裡面先做運算,我自己也在getcontext().prec這裡設定錯誤了。 再次謝謝大家協助解惑 ※ 編輯: doun (27.105.26.14), 02/11/2018 21:01:49
vfgce: 另外一個解法,使用sympy.. 02/12 13:56
vfgce: from sympy import S;S('156/283').n(30) 02/12 13:58
vfgce: n()可以設定要的精確度............ 02/12 13:59
ar54971: https://goo.gl/2WCUGr 03/06 03:41
galeondx: https://goo.gl/cybm9m 03/06 04:19
galeondx: https://goo.gl/MKaCK6 03/06 04:32
galeondx: https://tinyurl.com/yadsk3lo 03/06 04:45