Last active
July 15, 2022 00:26
-
-
Save matheusfillipe/fccd452a769d33df4cc27d8fbfdf1439 to your computer and use it in GitHub Desktop.
Compute pi with common lisp using leibnix formula
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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