简体   繁体   中英

Million decimal places in Python

We recently delve into infinite series in calculus and that being said, I'm having so much fun with it. I derived my own inverse tan infinte series in python and set to 1 to get pi/4*4 to get pi. I know it's not the fastest algorithm, so please let's not discuss about my algorithm. What I would like to discuss is how do I represent very very small numbers in python. What I notice is as my programs iterate the series, it stops somewhere at the 20 decimal places (give or take). I tried using decimal module and that only pushed to about 509. I want an infinite (almost) representation.

Is there a way to do such thing? I reckon no data type will be able to handle such immensity, but if you can show me a way around that, I would appreciate that very much.

Python's decimal module requires that you specify the "context," which affects how precise the representation will be.

I might recommend gmpy2 for this type of thing - you can do the calculation on rational numbers (arbitrary precision) and convert to decimal at the last step.

Here's an example - substitute your own algorithm as needed:

import gmpy2
# See https://gmpy2.readthedocs.org/en/latest/mpfr.html
gmpy2.get_context().precision = 10000
pi = 0
for n in range(1000000):
    # Formula from http://en.wikipedia.org/wiki/Calculating_pi#Arctangent
    numer = pow(2, n + 1)
    denom = gmpy2.bincoef(n + n, n) * (n + n + 1)
    frac = gmpy2.mpq(numer, denom)
    pi += frac
    # Print every 1000 iterations
    if n % 1000 == 0:
        print(gmpy2.mpfr(pi))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM