Search code examples
pythonpython-2.7savepi

How to save an indefinite number (up to the point that has been calculated)


I am currently calculating pi and the script I'm using doesn't stop after a certain point and, since Python loses your input after a certain point, I was wondering how I could save all I calculated. Here's the script that i'm using: EDIT: i was still new to python after finding this, tweaking it, and woundering how to save, i have since learned the obvios sultion of saving to to a file.

def calcPi():
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    while True:
        if (4*q+r-t < n*t):
            yield n
            nr = 10*(r-n*t)
            n  = ((10*(3*q+r))//t)-10*n
            q  *= 10
            r  = nr
        else:
            nr = (2*q+r)*l
            nn = (q*(7*k)+2+(r*l))//(t*l)
            q  *= k
            t  *= l
            l  += 2
            k += 1
            n  = nn
            r  = nr

import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
    sys.stdout.write(str(d))
    i   += 1
    if i == 40: 
       print("")
       i = 0

Solution

  • The only way to do this that I am aware of is to write the output to a file. The modified code below opens a file pi_out.txt, writes the first hundred digits of pi to it and then closes the file at the end.

    import sys
    
    def calcPi():
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    while True:
        if 4*q+r-t < n*t:
            yield n
            nr = 10*(r-n*t)
            n  = ((10*(3*q+r))//t)-10*n
            q  *= 10
            r  = nr
        else:
            nr = (2*q+r)*l
            nn = (q*(7*k)+2+(r*l))//(t*l)
            q  *= k
            t  *= l
            l  += 2
            k += 1
            n  = nn
            r  = nr
    
    pi_digits = calcPi()
    pi_out = open('pi_out.txt','w')
    
    i = 0
    j = 0 #number of digits of pi to find and output
    for d in pi_digits:
        sys.stdout.write(str(d))
        print >> pi_out, d
        i   += 1
        j   += 1
        if i == 40: print(""); i = 0
        if j == 100: break #breaks loop after finding appropriate digits of pi
    
    pi_out.close() #IMPORTANT Always close files
    

    Alternatively you could do this directly inside the function and have it output inside the file each time you call yield.