Skip to content

Instantly share code, notes, and snippets.

@rubik
Last active December 22, 2015 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubik/6391350 to your computer and use it in GitHub Desktop.
Save rubik/6391350 to your computer and use it in GitHub Desktop.
Computing PI digit by digit. The input to the function is the number of decimal digits.
f=lambda w=4:(lambda j,o,i:(lambda s,g:list(i.takewhile(lambda _:len(o)<w+1,
(((4*g(0)+g(1)-g(2)<g(4)*g(2)and(o.append(int(g(4))),s(6,10*(g(1)-g(4)*g(2))),
s(4,((10*(3*g(0)+g(1)))//g(2))-10*g(4)),s(0,g(0)*10),s(1,g(6))))or(s(6,(2*g(0)
+g(1))*g(5)),s(7,(g(0)*(7*g(3))+2+(g(1)*g(5)))//(g(2)*g(5))),s(0,g(0)*g(3)),
s(2,g(2)*g(5)),s(5,g(5)+2),s(3,g(3)+1),s(4,g(7)),s(1,g(6))))for _ in iter(int,1)
)))and o)(lambda v,y:j.__setitem__(v,y),lambda v:j[v]))([1,0,1,1,3,3,-1,-1],[],
__import__('itertools'))
@rubik
Copy link
Author

rubik commented Nov 22, 2013

Original code:

def ndig(w):
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    while w:
        if 4*q+r-t < n*t:
            yield int(n)
            w -= 1
            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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment