rand()
randn()
function rv = determinist()
rv = 1
end
Random variable $X$
function f=plot_avg(n,rv,avg)
xs = rv(n);
ns = 1:n;
s=0;
for i=1:n
ss(i) = xs(i) + s;
s = s + xs(i);
end
ss = ss ./ ns;
f=plot(ns,ss);
hold on;
plot(ns, 0*ns + avg);
hold off;
end
function f=plot_var(n,rv,var)
xs = rv(n);
ns = 1:n;
s=0;
s2=0;
for i=1:n
s = s + xs(i);
s2 = s2 + xs(i) .^ 2;
ss(i) = s2 ./ i - (s ./ i) .^ 2 ;
end
f=plot(ns,ss);
hold on;
plot(ns, 0*ns + var);
hold off;
end
clf();
nh = 100;
h = zeros(1,6);
for i = 1:nh
d = dice(1);
h(d) = h(d) + 1;
end
h = h ./ nh;
f = stem(h);
hold on;
plot(1:6, ones(6,1) / 6, 'k--' )
n_b=10;
delta = 1/n_b;
n_sample = 1000;
h = zeros(1,n_b);
for i = 1:n_sample;
x = rand();
k = ceil( x * n_b );
h(k) = h(k) + 1;
end
h = h ./ ( n_sample * delta )
for i = 1:n_b
rectangle('Position',
[ (a + (i-1) * delta) 0 delta h(i)],
'FaceColor','b' );
end
function d = dice()
u = rand();
for k=1:6
if u < k / 6
d=k
return
end
end
function [x,y] = disc_rand()
while true
%draw x,y in the square [-1,1]^2
x = 2 * rand() - 1
y = 2 * rand() - 1
% if they are in the disc, exit the loop
if x^2 + y^2 < 1
return
end
% otherwise try again
end
end
function [x,y,z] = tetrahedron_rand()
while true
%draw x,y in the cube [0,1]^3
x = rand()
y = rand()
z = rand()
% if they are inside the tetrahedron, exit the loop
if x + y + z < 1
return
end
% otherwise try again
end
end
function x = uniform_reject(f,m)
while true
%draw x, y in [0,1]*[0,m]
x = rand()
y = m * rand()
% if they are in the disc, exit the loop
if y < f(x)
return
end
% otherwise try again
end
end