source: proiecte/pmake3d/make3d_original/Make3dSingleImageStanford_version0.1/third_party/lightspeed/randbinom.m @ 37

Last change on this file since 37 was 37, checked in by (none), 14 years ago

Added original make3d

File size: 1.2 KB
Line 
1function r = randbinom(p, n)
2%RANDBINOM   Sample from a binomial distribution.
3% RANDBINOM(P,N) returns a sample from a binomial distribution with
4% parameters P and N (scalars).  Each sample ranges 0 to N.
5% It is more efficient than BINORND in the statistics toolbox.
6
7%   References:
8%      [1]  L. Devroye, "Non-Uniform Random Variate Generation",
9%      Springer-Verlag, 1986
10%
11% Also see: Kachitvichyanukul, V., and Schmeiser, B. W.
12% "Binomial Random Variate Generation." Comm. ACM, 31, 2 (Feb. 1988), 216.
13
14% Written by Tom Minka
15
16if isnan(p) | isnan(n)
17  r = nan;
18  return
19end
20
21if n < 15
22
23  % coin flip method
24  % this takes O(n) time
25  r = 0;
26  for i = 1:n
27    if rand < p
28      r = r + 1;
29    end
30  end
31
32elseif n*p < 150
33 
34  % waiting time method
35  % this takes O(np) time
36  q = -log(1-p);
37  r = n;
38  e = -log(rand);
39  s = e/r;
40  while(s <= q)
41    r = r - 1;
42    if r == 0
43      break
44    end
45    e = -log(rand);
46    s = s + e/r;
47  end
48  r = n - r;
49 
50else
51
52  % recursive method
53  % this makes O(log(log(n))) recursive calls
54  i = floor(p*(n+1));
55  b = randbeta(i, n+1-i);
56  if b <= p
57    r = i + randbinom((p-b)/(1-b), n-i);
58  else
59    r = i - 1 - randbinom((b-p)/b, i-1);
60  end
61 
62end
Note: See TracBrowser for help on using the repository browser.