Reputation: 5152
Just trying the basic python Decimal module and it seems to not work (in jupyter notebook):
from decimal import *
getcontext().prec = 1
getcontext()
return Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
Decimal(0.111111)
return Decimal('0.11111100000000000143085543413690174929797649383544921875')
Any idea what is going on?
Upvotes: 5
Views: 1048
Reputation: 1249
It looks like a bug.
Update: This should be fixed in ipython 6.0+, which was released in April 2021. Here's the specific PR for the fix: https://github.com/ipython/ipykernel/pull/632
If you are checking your installed versions with pip or jupyter --version
, the specific library you are looking for is ipykernel
>= 6.0
*EDIT: 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*:
getcontext().prec = x
behaves normally.I've filed a bug with Jupyter - https://github.com/jupyter/notebook/issues/5260
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.
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 notebook --version
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.
Upvotes: 2