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...

- Code: Select all
`#!/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:

- Code: Select all
`PI to six decimal places = 3.141592...`

Iterations = 1530012...

AMIGA:amiga~/Desktop/Code/Shell> _