pythonmemoryfloating-pointdecimalprecision

How to get largest possible precision? (Python - Decimal)


I'm using the Decimal class for operations that requires precision.

I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle.

To set a certain precision it's simple:

import decimal
decimal.getcontext().prec = 123 #123 decimal precision

I tried to figure out the maximum precision the 'Decimal' class can compute:

print(decimal.MAX_PREC)
>> 999999999999999999

So I tried to set the precision to the maximum precision (knowing it probably won't work..):

decimal.getcontext().prec = decimal.MAX_PREC

But, of course, this throws a Memory Error (on division)

So my question is: How do I figure out the maximum precision the current system can handle?

Extra info:

import sys
print(sys.maxsize)
>> 9223372036854775807

Solution

  • From your reply above:

    What if I just wanted to find more digits in pi than already found? what if I wanted to test the irrationality of e or mill's constant.

    I get it. I really do. My one SO question, several years old, is about arbitrary-precision floating point libraries for Python. If those are the types of numerical representations you want to generate, be prepared for the deep dive. Decimal/FP arithmetic is notoriously tricky in Computer Science.

    Some programmers, when confronted with a problem, think “I know, I’ll use floating point arithmetic.” Now they have 1.999999999997 problems. – @tomscott

    I think when others have said it's a "mistake" or "it depends" to wonder what the max precision is for a Python Decimal type on a given platform, they're taking your question more literally than I'm guessing it was intended. You asked about the Python Decimal type, but if you're interested in FP arithmetic for educational purposes -- "to find more digits in pi" -- you're going to need more powerful, more flexible tools than Decimal or float. These built-in Python types don't even come close. Those are good enough for NASA maybe, but they have limits... in fact, the very limits you are asking about.

    That's what multiple-precision (or arbitrary-precision) floating point libraries are for: arbitrarily-precise representations. Want to compute pi for the next 20 years? Python's Decimal type won't even get you through the day.

    The fact is, multi-precision binary FP arithmetic is still kinda fringe science. For Python, you'll need to install the GNU MPFR library on your Linux box, then you can use the Python library gmpy2 to dive as deep as you like.

    Then, the question isn't, "What's the max precision my program can use?"

    It's, "How do I write my program so that it'll run until the electricity goes out?"

    And that's a whole other problem, but at least it's restricted by your algorithm, not the hardware it runs on.