PI day.

Hi guys and gals...
OSX 10.13.3, default bash terminal calling ksh in the code.
I decided to have a go at creating PI using ksh only as a bit of fun.
I also decided on a Taylor series to do such a task.
This was the fun bit of code that generates PI to 6 decimal places although it could easily be set to continuous running and calculate within the limits of ksh's floating point precision.
It takes around 35 seconds to calculate to six decimal places...

#!/bin/ksh
# !/usr/local/bin/dash
# PI using the Taylor series.
# PI/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11......

clear
OP="-"
BASE=3.0
VAL=1.0
N=1
MYPI=0.0
while true
do
	if [ $(( $N % 2 )) -eq 0 ]
	then
		OP="+"
	fi
	if [ $(( $N % 2 )) -gt 0 ]
	then
		OP="-"
	fi
	VAL=$(( ($VAL * 1.0) $OP (1.0 / $BASE) ))
	BASE=$(( $BASE + 2.0 ))
	N=$(( $N + 1 ))
	MYPI=$(( $VAL * 4.0 ))
	# Hard coded known value to exit loop without interaction.
	if [ "${MYPI:0:8}" == "3.141592" ]
	then
		break
	fi
done
printf "PI to six decimal places = %.6f...\nIterations = $N...\n" "$MYPI"

Result:

PI to six decimal places = 3.141592...
Iterations = 1530012...
AMIGA:amiga~/Desktop/Code/Shell> _

Enjoy and hope to see other solutions on this thread...

I had to do this in awk as I don't have ksh installed, but I think you get the gist... Usually, an iteration is exited if changes get below a defined bound which I here chose to be 10^-7...

awk -vOFMT="%.8f" '
BEGIN   {SGN = BS = 1

         do     {OLD  = PI4
                 PI4 += SGN/BS
                 SGN *= -1
                 BS  += 2
                 DLT  = OLD - PI4
                }
         while (DLT>0?DLT:-DLT > 1E-7)

         print PI4*4, 4*atan2(1,1), 22/7
        }
'
3.14159285 3.14159265 3.14285714
1 Like