About me

About me

Feeds

RSS feed

Calculating the digits of pi

10th March 2026

One of the examples I wanted to include for my Simple infinite precision arithmetic package is a function to calculate an arbitrary number of digits of π. I finally got it working, so here it is.

Digits of π

The formula is based on the following equation found by John Machin, an 18th century astronomer and mathematician:

π4
= 4 arctan
15
– arctan
1239

If you're wondering where the values 5 and 239 come from, see the Wikipedia article [1].

The two arctangents can be calculated using the arctangent series:

arctan x = x –
x33
+
x55
x77
+ ...

Machin's formula converges extremely rapidly, making it a widely used method of calculating π to a large number of digits.

Here's the function arctan that iteratively calculates the arctangent of 1/x with a scale factor of n:

(defun arctan (n x)
  (let* ((i 0) 
         (xn (div n x))
         (x2 (mul x x))
         (term xn)
         result)
    (loop
     (setq result 
           (if (evenp i) (add result term)
             (sub result term)))
     (incf i)
     (setq xn (div xn x2))
     (setq term (div xn (bign (1+ (* 2 i)))))
     (when (null term) (return result)))))

So to calculate arctan 1/5 to 8 digits evaluate:

> (pri (arctan (big 100000000) (big 5)))
19739557

Compare this with the calculation using floating-point arithmetic:

> (atan (/ 1 5))
0.19739557

Finally, the function machin calculates π to d digits using Machin's formula:

(defun machin (d)
  (let ((n (iex 10 d)))
    (mul (big 4) (sub (mul (big 4) (arctan n (big 5))) (arctan n (big 239))))))

Here's π to 80 digits:

> (pri (machin 80))
314159265358979323846264338327950288419716939937510582097494459230781640628620948

  1. ^ Machin-like formula on Wikipedia.

blog comments powered by Disqus