1

I'm using jupyter notebook with anaconda on windows (reinstalled to the current version after several attempts). Somehow the mpmath library stopped working. Consider the following code

import mpmath as mp
mp.dps=530
mp.mpf(1) / mp.mpf(6)

But the result I got was

mpf('0.16666666666666666')

I also tried

mp.mpf("1") / mp.mpf("6")

which returned the same thing, and

mp.nprint(mp.mpf(1) / mp.mpf(6),50)

returned

0.16666666666666665741480812812369549646973609924316

which indicated the module malfunctioned.

What went wrong with the code?

1 Answers1

2

You're not changing the context - you're adding a (useless) dps attribute to the mpmath module itself.

Let's do it without renaming gimmicks to make it clearer:

>>> import mpmath
>>> mpmath.dps = 530
>>> mpmath.mpf(1) / mpmath.mpf(6)
mpf('0.16666666666666666')

What you wanted instead is to set dps on the mp context attribute of the mpmath module:

>>> import mpmath
>>> mpmath.mp.dps = 530 # note that this is different!
>>> mpmath.mpf(1) / mpmath.mpf(6)
mpf('0.16666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666675')

For this reason, you should never do import mpmath as mp - it's just begging to confuse (as happened to you) the module with the module's context object.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
  • Thank you so much. This is so useful, I tried mp.mp.dps=530 and it worked. Somehow I must had been develop the code in the default mode, i.e. "import mpmath" so it did not occur. Is it possible to rename the context differently from "mp"? i.e. "mp.default.dps" ? I'm not sure if this is a bad habit or not, since everyone uses sp and np etc. – ShoutOutAndCalculate Aug 01 '23 at 22:06
  • 1
    I typically do stuff like `from mpmath import mpf, mp as ctx`. Then, e.g., `ctx.dps = 600; mpf(1) / mpf(6)` works fine. In interactive mode, you won't actually be attacked ;-) if you do `from mpmath import *` and then use `mpf` and `mp` (etc) directly. – Tim Peters Aug 01 '23 at 22:11