How to fix the ZeroDivisionError with 1000 decimals digits output in Python?

Question:

In the following 2 examples:

Example 1:

from decimal import Decimal, getcontext
getcontext().prec = 1000
d = Decimal(1+10**(-24))
1/d.ln()

Example 2:

from mpmath import *
mp.dps = 1000
mp.pretty=True
1/(ln(1+10**(-24)))

I get the ZeroDivisionError. Python 3.7(64-bit) takes it as 1/ln(1) or 1/0.

How I can make Python read it as 1/ln(1+10^(-24)) not 1/ln(1)?

Asked By: Psylife

||

Answers:

  • For example #1, make everything a Decimal resulting from operations between Decimal:
d = Decimal(1) + Decimal(10) ** Decimal(-24) # Decimal('1.000000000000000000000001')
Decimal(1) / d.ln()

otherwise you’d get a primitive type float precision first, and the number rounded to 1.0:

1+10**(-24) # 1.0
Decimal(1+10**(-24)) # 1
  • Similarly, for example #2 (I just have read now the docs for mpmath, so take it with a grain of salt):
from mpmath import mp, mpf, ln
    
mp.dps = 1000
mp.pretty = True
    
mpf(1) / ln(mpf(1) + mpf(10) ** mpf(-24))
Answered By: Jonathan Ciapetti