Python Decimal不接受getcontext()精度修改 [英] Python Decimal not accepting getcontext() precision modifications

查看:97
本文介绍了Python Decimal不接受getcontext()精度修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需尝试基本的 python十进制模块似乎不起作用(在jupyter笔记本中):

Just trying the basic python Decimal module and it seems to not work (in jupyter notebook):

from decimal import *
getcontext().prec = 1

getcontext()

返回 Context(prec = 28,舍入= ROUND_HALF_EVEN,Emin = -999999,Emax = 999999,大写字母= 1,clamp = 0,标志= [],陷阱= [InvalidOperation,DivisionByZero,溢出])

Decimal(0.111111)

返回十进制('0.11111100000000000143085543413690174929797649383544921875')

知道发生了什么吗?

推荐答案

它看起来像个错误.

* 行为似乎因版本而异.最可靠的解决方法应该是在需要应用的每个单元格中定义小数精度,或者将精度定义移至外部模块.

* Behavior seems to vary depending on versions. The most reliable workaround should be to define decimal precision within each cell where you need it to apply, or to move precision definitions to external modules.

我已经进行了一些故障排除,这是我发现的内容*:

I've done some troubleshooting and here's what I found*:

  • 如果您刚刚启动Jupyter,则 getcontext().prec = x 的行为正常.
  • 如果使用运行">运行所有单元",则行为也是正常的.
  • 如果您在Jupyter UI中重新启动内核,则在手动执行单元之间,精度会重置为28.

我向Jupyter提交了一个错误- https://github.com/jupyter/笔记本/问题/5260

I've filed a bug with Jupyter - https://github.com/jupyter/notebook/issues/5260

作为一种简单但丑陋的解决方法,在希望应用精度的每个单元格中定义 getcontext().prec = 1 似乎迫使Jupyter使用它.

As an easy but kind of ugly workaround, defining getcontext().prec = 1 in each cell where you want that precision applied appears to force Jupyter to use that.

或者-这很奇怪-在任何单元格中运行此命令似乎可以修复整个笔记本计算机运行后的精度.把它放在您的nb顶部,您应该会很好:

Or - this is quite strange - running this command in any cell appears to fix precision for the entire notebook after it is run. Put it at the top of your nb and you should be good:

!jupyter笔记本--version

最后,导入的模块应正常运行.如果您走这条路,我可能建议您使用"nbdev"包之类的东西来简化从笔记本计算机创建模块的过程-与从笔记本计算机复制/粘贴相比,这样使组织起来更加容易.

Finally, imported modules should behave normally. If you go that route, I might suggest using something like the 'nbdev' package to streamline the process of creating modules from notebooks - it makes it a lot easier to keep organized than copy/pasting from notebooks.

这篇关于Python Decimal不接受getcontext()精度修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆