blob: e408d21da1617bb60dcd454f6fdae321f92a5d1a [file] [log] [blame]
Guido van Rossum260cc1a81992-08-10 10:48:14 +00001# Display digits of pi in a window, calculating in a separate thread.
2# Compare ../scripts/pi.py.
3
4import time
5import thread
6import stdwin
7from stdwinevents import *
8
9digits = []
10
11def worker():
12 k, a, b, a1, b1 = 2l, 4l, 1l, 12l, 4l
13 while 1:
14 # Next approximation
15 p, q, k = k*k, 2l*k+1l, k+1l
16 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
17 # Print common digits
18 d, d1 = a/b, a1/b1
19 #print a, b, a1, b1
20 while d == d1:
21 digits.append(`int(d)`)
22 a, a1 = 10l*(a%b), 10l*(a1%b1)
23 d, d1 = a/b, a1/b1
24
25def main():
26 digits_seen = 0
27 thread.start_new_thread(worker, ())
28 tw = stdwin.textwidth('0 ')
29 lh = stdwin.lineheight()
30 stdwin.setdefwinsize(20 * tw, 20 * lh)
31 win = stdwin.open('digits of pi')
32 options = win.menucreate('Options')
33 options.additem('Auto scroll')
34 autoscroll = 1
35 options.check(0, autoscroll)
36 while 1:
37 win.settimer(1)
38 type, w, detail = stdwin.getevent()
39 if type == WE_CLOSE:
40 thread.exit_prog(0)
41 elif type == WE_DRAW:
42 (left, top), (right, bottom) = detail
43 digits_seen = len(digits)
44 d = win.begindrawing()
45 for i in range(digits_seen):
46 h = (i % 20) * tw
47 v = (i / 20) * lh
48 if top-lh < v < bottom:
49 d.text((h, v), digits[i])
50 d.close()
51 elif type == WE_TIMER:
52 n = len(digits)
53 if n > digits_seen:
54 win.settitle(`n` + ' digits of pi')
55 d = win.begindrawing()
56 for i in range(digits_seen, n):
57 h = (i % 20) * tw
58 v = (i / 20) * lh
59 d.text((h, v), digits[i])
60 d.close()
61 digits_seen = n
62 height = (v + 20*lh) / (20*lh) * (20*lh)
63 win.setdocsize(0, height)
64 if autoscroll:
65 win.show((0, v), (h+tw, v+lh))
66 elif type == WE_MENU:
67 menu, item = detail
68 if menu == options:
69 if item == 0:
70 autoscroll = (not autoscroll)
71 options.check(0, autoscroll)
72
73
74main()