Improve spelling
[alexandria.git] / numbers.lisp
blob9ced84b33ff9991a989b6bd37593d3bdb04ce005
1 (in-package :alexandria)
3 (declaim (inline clamp))
4 (defun clamp (number min max)
5 "Clamps the NUMBER into [min, max] range. Returns MIN if NUMBER is lesser then
6 MIN and MAX if NUMBER is greater then MAX, otherwise returns NUMBER."
7 (if (< number min)
8 min
9 (if (> number max)
10 max
11 number)))
13 (defun gaussian-random (&optional min max)
14 "Returns two gaussian random double floats as the primary and secondary value,
15 optionally constrained by MIN and MAX. Gaussian random numbers form a standard
16 normal distribution around 0.0d0.
18 Sufficiently positive MIN or negative MAX will cause the algorithm used to
19 take a very long time. If MIN is positive it should be close to zero, and
20 similarly if MAX is negative it should be close to zero."
21 (labels ((gauss ()
22 (loop
23 for x1 = (- (random 2.0d0) 1.0d0)
24 for x2 = (- (random 2.0d0) 1.0d0)
25 for w = (+ (expt x1 2) (expt x2 2))
26 when (< w 1.0d0)
27 do (let ((v (sqrt (/ (* -2.0d0 (log w)) w))))
28 (return (values (* x1 v) (* x2 v))))))
29 (guard (x min max)
30 (unless (<= min x max)
31 (tagbody
32 :retry
33 (multiple-value-bind (x1 x2) (gauss)
34 (when (<= min x1 max)
35 (setf x x1)
36 (go :done))
37 (when (<= min x2 max)
38 (setf x x2)
39 (go :done))
40 (go :retry))
41 :done))
42 x))
43 (multiple-value-bind (g1 g2) (gauss)
44 (values (guard g1 (or min g1) (or max g1))
45 (guard g2 (or min g2) (or max g2))))))
47 (declaim (inline iota))
48 (defun iota (n &key (start 0) (step 1))
49 "Return a list of n numbers, starting from START (with numeric contagion
50 from STEP applied), each consequtive number being the sum of the previous one
51 and STEP. START defaults to 0 and STEP to 1.
53 Examples:
55 (iota 4) => (0 1 2 3 4)
56 (iota 3 :start 1 :step 1.0) => (1.0 2.0 3.0)
57 (iota 3 :start -1 :step -1/2) => (-1 -3/2 -2)
59 (declare (type (integer 0) n) (number start step))
60 (loop repeat n
61 ;; KLUDGE: get numeric contagion right for the first element too
62 for i = (+ start (- step step)) then (+ i step)
63 collect i))
65 (declaim (inline map-iota))
66 (defun map-iota (function n &key (start 0) (step 1))
67 "Calls FUNCTION with N numbers, starting from START (with numeric contagion
68 from STEP applied), each consequtive number being the sum of the previous one
69 and STEP. START defaults to 0 and STEP to 1. Returns N.
71 Examples:
73 (map-iota #'print 3 :start 1 :step 1.0) => 3
74 ;;; 1.0
75 ;;; 2.0
76 ;;; 3.0
78 (declare (type (integer 0) n) (number start step))
79 (loop repeat n
80 ;; KLUDGE: get numeric contagion right for the first element too
81 for i = (+ start (- step step)) then (+ i step)
82 do (funcall function i))
85 (declaim (inline lerp))
86 (defun lerp (v a b)
87 "Returns the result of linear interpolation between A and B, using the
88 interpolation coefficient V."
89 (+ a (* v (- b a))))
91 (declaim (inline mean))
92 (defun mean (sample)
93 "Returns the mean of SAMPLE. SAMPLE must be a sequence of numbers."
94 (/ (reduce #'+ sample) (length sample)))
96 (declaim (inline median))
97 (defun median (sample)
98 "Returns median of SAMPLE. SAMPLE must be a sequence of real numbers."
99 (let* ((vector (sort (copy-sequence 'vector sample) #'<))
100 (length (length vector))
101 (middle (truncate length 2)))
102 (if (oddp length)
103 (aref vector middle)
104 (/ (+ (aref vector middle) (aref vector (1- middle))) 2))))
106 (declaim (inline variance))
107 (defun variance (sample &key (biased t))
108 "Variance of SAMPLE. Returns the biased variance if BIASED is true (the default),
109 and the unbiased estimator of variance if BIASED is false. SAMPLE must be a
110 sequence of numbers."
111 (let ((mean (mean sample)))
112 (/ (reduce (lambda (a b)
113 (+ a (expt (- b mean) 2)))
114 sample
115 :initial-value 0)
116 (- (length sample) (if biased 0 1)))))
118 (declaim (inline standard-deviation))
119 (defun standard-deviation (sample &key (biased t))
120 "Standard deviation of SAMPLE. Returns the biased standard deviation if
121 BIASED is true (the default), and the square root of the unbiased estimator
122 for variance if BIASED is false (which is not the same as the unbiased
123 estimator for standard deviation). SAMPLE must be a sequence of numbers."
124 (sqrt (variance sample :biased biased)))
126 (define-modify-macro maxf (&rest numbers) max
127 "Modify-macro for MAX. Sets place designated by the first argument to the
128 maximum of its original value and NUMBERS.")
130 (define-modify-macro minf (&rest numbers) min
131 "Modify-macro for MIN. Sets place designated by the first argument to the
132 minimum of its original value and NUMBERS.")
134 ;;;; Factorial
136 ;;; KLUDGE: This is really dependant on the numbers in question: for
137 ;;; small numbers this is larger, and vice versa. Ideally instead of a
138 ;;; constant we would have RANGE-FAST-TO-MULTIPLY-DIRECTLY-P.
139 (defconstant +factorial-bisection-range-limit+ 8)
141 ;;; KLUDGE: This is really platform dependant: ideally we would use
142 ;;; (load-time-value (find-good-direct-multiplication-limit)) instead.
143 (defconstant +factorial-direct-multiplication-limit+ 13)
145 (defun %multiply-range (i j)
146 ;; We use a a bit of cleverness here:
148 ;; 1. For large factorials we bisect in order to avoid expensive bignum
149 ;; multiplications: 1 x 2 x 3 x ... runs into bignums pretty soon,
150 ;; and once it does that all further multiplications will be with bignums.
152 ;; By instead doing the multiplication in a tree like
153 ;; ((1 x 2) x (3 x 4)) x ((5 x 6) x (7 x 8))
154 ;; we manage to get less bignums.
156 ;; 2. Division isn't exactly free either, however, so we don't bisect
157 ;; all the way down, but multiply ranges of integers close to each
158 ;; other directly.
160 ;; For even better results it should be possible to use prime
161 ;; factorization magic, but Nikodemus ran out of steam.
163 ;; KLUDGE: We support factorials of bignums, but it seems quite
164 ;; unlikely anyone would ever be able to use them on a modern lisp,
165 ;; since the resulting numbers are unlikely to fit in memory... but
166 ;; it would be extremely unelegant to define FACTORIAL only on
167 ;; fixnums, _and_ on lisps with 16 bit fixnums this can actually be
168 ;; needed.
169 (labels ((bisect (j k)
170 (declare (type (integer 1 #.most-positive-fixnum) j k))
171 (if (< (- k j) +factorial-bisection-range-limit+)
172 (multiply-range j k)
173 (let ((middle (+ j (truncate (- k j) 2))))
174 (* (bisect j middle)
175 (bisect (+ middle 1) k)))))
176 (bisect-big (j k)
177 (declare (type (integer 1) j k))
178 (if (= j k)
180 (let ((middle (+ j (truncate (- k j) 2))))
181 (* (if (<= middle most-positive-fixnum)
182 (bisect j middle)
183 (bisect-big j middle))
184 (bisect-big (+ middle 1) k)))))
185 (multiply-range (j k)
186 (declare (type (integer 1 #.most-positive-fixnum) j k))
187 (do ((f k (* f m))
188 (m (1- k) (1- m)))
189 ((< m j) f)
190 (declare (type (integer 0 (#.most-positive-fixnum)) m)
191 (type unsigned-byte f)))))
192 (bisect i j)))
194 (declaim (inline factorial))
195 (defun %factorial (n)
196 (if (< n 2)
198 (%multiply-range 1 n)))
200 (defun factorial (n)
201 "Factorial of non-negative integer N."
202 (check-type n (integer 0))
203 (%factorial n))
205 ;;;; Combinatorics
207 (defun binomial-coefficient (n k)
208 "Binomial coefficient of N and K, also expressed as N choose K. This is the
209 number of K element combinations given N choises. N must be equal to or
210 greater then K."
211 (check-type n (integer 0))
212 (check-type k (integer 0))
213 (assert (>= n k))
214 (if (or (zerop k) (= n k))
216 (let ((n-k (- n k)))
217 ;; Swaps K and N-K if K < N-K because the algorithm
218 ;; below is faster for bigger K and smaller N-K
219 (when (< k n-k)
220 (rotatef k n-k))
221 (if (= 1 n-k)
223 ;; General case, avoid computing the 1x...xK twice:
225 ;; N! 1x...xN (K+1)x...xN
226 ;; -------- = ---------------- = ------------, N>1
227 ;; K!(N-K)! 1x...xK x (N-K)! (N-K)!
228 (/ (%multiply-range (+ k 1) n)
229 (%factorial n-k))))))
231 (defun subfactorial (n)
232 "Subfactorial of the non-negative integer N."
233 (check-type n (integer 0))
234 (if (zerop n)
236 (do ((x 1 (1+ x))
237 (a 0 (* x (+ a b)))
238 (b 1 a))
239 ((= n x) a))))
241 (defun count-permutations (n &optional (k n))
242 "Number of K element permutations for a sequence of N objects.
243 K defaults to N"
244 (check-type n (integer 0))
245 (check-type k (integer 0))
246 (assert (>= n k))
247 (%multiply-range (1+ (- n k)) n))