Post Reply 
Pi digits (again) - an unbounded spigot program
05-19-2024, 03:47 AM (This post was last modified: 05-19-2024 07:16 AM by komame.)
Post: #20
RE: Pi digits (again) - an unbounded spigot program
(05-18-2024 03:19 PM)Guenter Schink Wrote:  output is the same as Thomas'
time is between 5 and 6.5 seconds with several runs

If performance is important, this code can be optimized by buffering the result in a variable and then outputting it to the terminal all at once, instead of outputting partial results multiple times.

Code:
from hpprime import *

def main(n, k):
    eval('PRINT')
    s = ''
    a=eval('time')
    init = ((1, 0, 0, 1), 1)
    lfts = (
        (i * (2 * i - 1), j * (5 * i - 2), 0, j)
        for i, j in ((i, 3 * (3 * i + 1) * (3 * i + 2)) for i in range(1, n))
    )
    pi = stream(init, lfts)
    i = 0
    for d in pi:
        s += str(d)
        if i % k == 0:
            s += '\n'
        i += 1
    a=round(eval('time')-a,4)
    print(s)
    print("\n",a)

def stream(u, lfts):
    for x in lfts:
        v = cons(u, x)
        y = next(v)
        yield y
        u = prod(v, y)

def next(z):
    [[q, r, s, t], i] = z
    x = 27 * i + 15
    return (q * x + 5 * r) // (s * x + 5 * t)

def prod(s, n):
    z, i = s
    return comp((10, -10 * n, 0, 1), z), i

def cons(s, x):
    z, i = s
    return comp(z, x), i + 1

def comp(a, b):
    q, r, s, t = a
    u, v, w, x = b
    return q * u + r * w, q * v + r * x, s * u + t * w, s * v + t * x

#if __name__ == "__main__":
if 1==1:
    n, k = 1002, 25
    main(n, k)

This reduces the execution time of this task on the HP Prime to below 1 second (significant acceleration).

Piotr Kowalewski
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Pi digits (again) - an unbounded spigot program - komame - 05-19-2024 03:47 AM



User(s) browsing this thread: 1 Guest(s)