% % use acceptance-rejection method to generate random variables from a beta distribution with % alpha = 2 and beta = 1. % % Here: f(x) = 2 x 0 < x < 1 % % Written by: % -- % John L. Weatherwax 2008-02-20 % % email: wax@alum.mit.edu % % Please send comments and especially bug reports to the % above email address. % %----- clear all; close all; c = 2; n = 1000; x = zeros(1,n); xy = zeros(1,n); rej = zeros(1,n); rejy = zeros(1,n); irv = 1; irej = 1; while( irv <= n ) y = rand(1); u = rand(1); if( u <= (2*y)/(c*1) ) % <- 2*y is the "difficult" density to sample from ... 1 is the uniform density x(irv) = y; xy(irv) = u*c; irv = irv+1; else rej(irej) = y; % <- if more than n rejections happen Matlab will grow this vector as needed. rejy(irej) = u*c; irej = irej+1; end end fprintf('the number rejected=%10d; total number generated=%10d; efficiency=%10.6f\n',irej,irv+irej,irv/(irv+irej));