Skip to content

Instantly share code, notes, and snippets.

@matheusfillipe
Last active July 15, 2022 00:26
Show Gist options
  • Save matheusfillipe/fccd452a769d33df4cc27d8fbfdf1439 to your computer and use it in GitHub Desktop.
Save matheusfillipe/fccd452a769d33df4cc27d8fbfdf1439 to your computer and use it in GitHub Desktop.
Compute pi with common lisp using leibnix formula
;; Way to compute pi in common lisp using Leibniz formula
(defun ^ (x n)
(if (> n 0)
(* x (^ x (- n 1)))
(if (< n 0)
(* (/ 1 x) (^ x (+ n 1)))
1)))
(defun oddnum (n) (+ (* 2 n) 1))
(defun sum (numbers)
(reduce
(lambda (x y) (+ x y))
numbers))
(defun N (start end &optional acc)
(if (< end start)
acc
(N start
(- end 1)
(cons end acc))))
(defun pirange (start end)
(* 4 (sum
(mapcar
(lambda (x) (/ (^ -1 x)
(oddnum x)))
(N start end))))
)
(let ((mypi 0))
(setq mypi (+ mypi (pirange 0 10000)))
(princ "Approximation of pi: ")
(print (coerce mypi 'long-float)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment