Mpmath variable precision by comparing results at different precisions

24 views Asked by At

I have a function that - depending on the factors - requires a varying level of precision. I could set an arbitrarily large mp.dps decimal-count, but that's slow and the needed precision is unknown (could be mp.dps=50 or mp.dps=10^4).

My current solution is to double the decimals and check if they're equal (have converged). This works and the chance of collision (false-positive) seems small.

from mpmath import mp
import math

# Miscellaneous large factors
factors = [5125453, 114233124, 312341231, 8124123, 15124123]
# Number of decimals to use for floats
mp.dps = 5

# Test function; requires precise floats.
r1 = sum([math.prod(factors)/mp.mpf(factor) for factor in factors])
mp.dps *= 2
r2 = sum([math.prod(factors)/mp.mpf(factor) for factor in factors])

while r1 != r2:
    print(f"Doubling decimals!; {mp.dps} -> {mp.dps * 2}; {r1} != {r2}")
    r1 = r2
    mp.dps *= 2
    r2 = sum([math.prod(factors) / mp.mpf(factor) for factor in factors])
print("r1 = r2", r1)
# Desired output: 8904132809408000116515634109283.0

Is there a better alternative to this to ensure the precision is enough?

If not, is there a way to make this more pythonic?

0

There are 0 answers