2

I'm trying to solve a numerical maths problem, and for that I need python to handle very small numbers. For that, I installed mpmath.
It doesn't quite work as desired though. Mpmath is able to handle 1e-300 but not 1e-400 (10^-300 but not 10^-400 respectively)

In the head I have

from mpmath import mp
from mpmath import mpf

mp.dps = 500 

If I type

x = mpf(1e-300)
print(x)

I get a thousand digit number, that is close to 1e-300 (which is what I want)

However, if I now type

y = mpf(1e-400)
print(y)

I get the result: 0.0, which is not what I want.

I tried to ramp up the decimal precision (e.g. mp.dps = 3000) but it didn't help, I still got zero in the second case.

Is there a way to circumvent this, or is mpmath just unable to do handle 1e-400?

  • python interprets the literal while it's lexing the document, and because 1e-400 isn't possible with regular python types, it is converted to 0.0 before being passed to the function – Aaron May 28 '20 at 18:04

1 Answers1

4

Issue is you're running into the accuracy of double floating point numbers

  • Doubles have a range of 1e-300 to 1e+300.
  • Provide the number to mpmath as a string so it converts it rather than passing a float

Meaning change from:

y = mpmath(1e-400) # 1e-400 becomes 0 as a 
                   # float due to limited
                   # doubles accuracy

To:

y = mpmath('1e-400')

Test

from mpmath import mp
from mpmath import mpf

mp.dps = 500 

y = mpf('1e-400')
for k in range(10):
  print(k*y)

Output

1.0e-400
2.0e-400
3.0e-400
4.0e-400
5.0e-400
6.0e-400
7.0e-400
8.0e-400
9.0e-400
DarrylG
  • 16,732
  • 2
  • 17
  • 23