1 #!/usr/bin/dc
2 #generate pi based on viete's formula
3 #viete's formula is pi/2 = sqrt(2)/2 * sqrt(2+sqrt(2))/2 ...
4 #this is easily computed using rpn, in dc it looks something like
5 #2 2v2/ 2v2+v2/* 2v2+v2+v2/* 2v2+v2+v2+v2/* /
6 #here i use two iterative macros
7 #one adds another string of '2v2+v2+v2+v2[...]/*'
8 #the other handles adding every individual '+v2' into that string
9
10 #clear screen
11 !clear
12
13 #set precision and number of iterations (i)
14 [Precision?]p
15 ?k
16 [Iterations?]p
17 ?si
18
19 #m is our 'main'
20 #put a 2 on the stack, resets counter a to zero, starts the action
21 #by running macro y, then once that's all done, divide it into the two
22 #we set at the beginning - since we solve for pi/2
23
24 [2 0salyx/p]sm
25
26 #y kicks things off. the first step makes little iterative sense
27 #the first step is 2v2/ compared to further steps which add multiple
28 #'+v2's and a trailing '*' - so step one we just write out, then run x
29
30 [2v2/plxx]sy
31
32 #x is our main iterator
33 #increment counter a by one
34 #reset counter b to 0
35 #start with '2v2'
36 #run macro 'w,' to repeat the roots
37 #perform the division into 2, print the result
38 #multiply it by the last result, print the result
39 #is counter a NOT equal to our target number of iterations?
40 #then run x again...
41
42 [la1+sa0sb2v2lwx/p*plila!=x]sx
43
44 #w is our repeating roots iterator
45 #increment counter b by one
46 #execute '+v2'
47 #is counter b NOT equal to the current iteration of macro x?
48 #then run w again…
49
50 [lb1+sb+v2lalb!=w]sw
51
52 #main()
53
54 lmx
55
56 #…back to brian hefele's untidy space…
56 #…or download this script, pi.dc…
56 #…or download this syntax definition, dc.vim.