Skip to content

Instantly share code, notes, and snippets.

@mheise
Created October 11, 2011 20:20
Show Gist options
  • Save mheise/1279289 to your computer and use it in GitHub Desktop.
Save mheise/1279289 to your computer and use it in GitHub Desktop.
Some common math implemented in common lisp
(defun sum(l)
(reduce #'+ l))
(defun avg (a &rest rest)
(/ (apply #'+ a rest) (+ 1 (length rest))))
(defun fact(n)
(if (or (= n 1) (= n 0))
1
(* n (fact (- n 1)))))
(defun fact-it (n)
"Iterative factorial implementation to avoid stack overflow"
(let ((prod 1))
(dotimes (i n prod)
(setf prod (* (+ i 1) prod)))))
(defun rect-int (f lo hi &key (steps 2000))
"Rectangular integral approximation"
(let ((step (/ (- hi lo) steps)))
(loop for i from lo below hi by step sum
(* step (funcall f i)))))
(defun trap-int (f lo hi &key (steps 2000))
"Trapezoidal integral approximation"
(let ((step (/ (- hi lo) steps)))
(loop for i from lo below hi by step sum
(* step (avg (funcall f i)
(funcall f (+ i step)))))))
(load "math.cl")
(defun choose (n k)
(/ (fact n) (* (fact k) (fact (- n k)))))
(defun geometric-pmf (p k)
"PMF for a geometric discrete random variable"
(* p (expt (- 1 p) (- k 1))))
(defun geometric-ex (p)
"Expected value for a geometric random variable"
(/ 1 p))
(defun poisson-pmf (a k)
"PMF for a Poisson discrete random variable"
(/ (* (expt a k) (exp (- a))) (fact k)))
(defun expected-value (l)
"Expected value for a nested list like '((.25 1) (.25 2) (.25 3) (.25 4))"
(sum (mapcar #'(lambda (i) (* (car i) (cadr i))) l)))
(defun exponential-pdf (la x)
"PDF for an exponential continuous random variable"
(* la (exp (- (* la x)))))
(defun exponential-cdf (la x)
"CDF for an exponential continuous random variable"
(if (< x 0)
0
(- 1 (exp (- (* la x))))))
(defun gaussian-pdf (x &key (mu 0) (sigma 1))
"Classic Gaussian or normal distribution"
(/ (exp (- (/ (expt (- x mu) 2)
(* 2 (expt sigma 2)))))
(* sigma (sqrt (* 2 pi)))))
(defun gaussian-cdf (lo hi &key (mu 0) (sigma 1))
"Numeric approximation of the CDF of a normal (Gaussian) distribution."
(trap-int #'(lambda (n) (gaussian-pdf n :mu mu :sigma sigma)) lo hi))
(defun phi (x &key (mu 0) (sigma 1))
"Numeric approximation of phi; used a lower bound of 10 to avoid floating
point underflow without much accuracy loss."
(gaussian-cdf -10 x :mu mu :sigma sigma))
(defun q (x &key (mu 0) (sigma 1))
"Numeric approximation of Q"
(- 1 (phi x :mu mu :sigma sigma)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment