Matlab probability converge

31 Views Asked by At

I have a homework problem ask me to use Monte Carlo simulations to validate the formulas, but I tried an easy example if I have a random variable uniformly in $[0,1]$, and I rand(n,1), with n increasing, the probability of having the number between $[0, 0.5]$ should be 0.5, but as I tried the codes :

format long
l = 0.5;
n = linspace(10^4,10^6,100);
for i = 1:length(n)
    a = rand(1,n(i));
    c = size(find(a <= 0.5))/n(i);
    b(i) = c(2);
end
error = b - 0.5;
error(90:100)

I get the result:

ans =

  Columns 1 through 6

   0.000808888888889  -0.000276923076923   0.001057608695652  -0.000254838709677   0.000546808510638  -0.000346315789474

  Columns 7 through 11

  -0.000016666666667   0.000226804123711   0.000191836734694   0.000285858585859  -0.000425000000000

so the error is still about 10^(-3) order and wont get smaller, I dont know why. Thank you for any help.