iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙃
Calculating Pi with dc(1)
This is something I couldn't finish in time for March 14th = Pi Day. It's a little trick using dc, which should be pre-installed in almost any Unix-like environment.
If you have some free time, try running the following command. After a while, the value of Pi (or something close to it) will be displayed.
$ echo '6k10K^1-[d2-d1<A]dsAx0dsasF[[lar-sa0sF]sZ]sC[[la+sa1sF]sZlF1=C1r/lZxz0<m]dsmx4la*p' | dc
If the processing time is too long and you can't wait, change the 6 at the beginning of the string passed to echo to a 5.
Explanation
This is a formula that those of you who spent your middle school days killing time with BASIC might find familiar. It's the one with rather slow convergence.
6k # Precision is 6 digits
10K^1-[d2-d1<A]dsAx # Enumerate all odd numbers
0dsasF # Initialize various registers
[[lar-sa0sF]sZ]sC # Macro to override for odd-numbered terms
[
[la+sa1sF]sZ # Assume it's an even-numbered term
lF1=C # Override if it's an odd-numbered term
1r/ # Convert to reciprocal
lZx # Addition process
z0<m # Loop until stack height is 1
]dsmx # Up to here is arctan(1)
4la*p # Display Pi
Discussion