A while back I shared some Perl code for calculating the circumference of a circle without knowing 𝛑. Just for fun, and due to my longtime infatuation with all things Schemish, I’ve written a little pi approximator in Scheme. It uses the idea that we can approximate a circle using smaller and smaller triangles stacked on top of each other. (See previously for a better explanation with a picture.)

And now, the code!

;;;; pi.scm -- Estimate the value of 𝛑 using smaller and smaller ;;;; triangles. ;;; Call it like so: (pi-estimate n), where n is the number of ;;; iterations you'd like to go through. It doesn't take many to get ;;; pretty accurate. (define reference-pi 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679) (define (circumference radius) (* 3.14159 2 radius)) (define (square x) (* x x)) (define (hypotenuse a b) (sqrt (+ (expt a 2) (expt b 2)))) (define (pi-iter radius a b count maxcount) (let* ((hyp (hypotenuse a b)) (newbase (- radius (sqrt (- (square radius) (square (/ hyp 2))))))) (if (= count maxcount) (/ (* 2 hyp (expt 2 (+ 1 count))) (* 2 radius)) (pi-iter radius newbase (/ hyp 2) (+ count 1) maxcount)))) (define (pi-estimate iterations) (pi-iter 128 128 128 0 iterations))

(Origami image courtesy Melisande under Creative Commons license.)

Advertisements