matlab - Random number generation - code not working as it should -


so have generate random number (called 'p' here) between 0 , 90 frequency distribution cosine function (i.e should have more numbers between 0 , 45 numbers between 45 , 90).

i working on matlab code follows -

flag = 1;  while flag == 1      candidate = randi([0,90]);     if rand < cosd( candidate )         p = candidate;         flag = 2;     end end   

i generating 20 such numbers of numbers towards higher end (45-90). 20 numbers, there hardly 1-2 numbers < 45.

is code wrong?

edit: okay, got answer. tried running code separately follows-

for = 1:20   flag = 1;    while flag == 1        candidate = randi([0,90]);       if rand < cosd( candidate )           p = candidate;           flag = 2;           disp(p);       end   end   end 

and i'm getting of values of p between 0 , 45. original code had external 'if' condition reason accepting higher values of 'p'. used while loop , number of iterations more 20 20 values of 'p'.

here original code snippet -

while zz <=20          d = randi([0,359]);         flag = 1;          while flag == 1              c = randi([0,90]);             x = rand(1);             if x < cosd(c)                 p = c;                 flag = 2;             end         end            if 'external condition'                strike(zz) = d;               dip(zz) = p;               slip(zz) = round(i);               zz= zz+1;         end  end 

if want answer, read last line. if want know why answer right, read explanation.

assume have distinct distribution function this:

f(0)=1; f(1.5)=10; f(4)=9; 

so cumulative function is:

f(0)=1; f(1.5)=11; f(4)=20; 

no want have relative cumulative function, f(4)=20 (4 last item), divide cumulative function 20. be:

f'(0)=0.05 f'(1.5)=0.55 f'(4)=1.00 

now, generate random number between 0 , 1. every time generate random number, generate value f'(x) , if f'(x) not have value anywhere, use nearest bigger number (like y) x, f(x)=y. example, based on relative cumulative function:

  • if random number less 0.05, our distribution-based random number 1.5

  • if random number between 0.05 , 0.55, our distribution-based random number 2,

  • if more 0.55, our distribution-based random number 4

we should similar work continuous distribution functions. difference in continuous world, use integral instead of cumulative function. question, have:

f(x)=cos(x) , 0<=x<=90 f(x)=sin(x)-sin(0)=sin(x) , 0<=x<=90 f'(x)=cos(x) , 0<=x<=90   (because f(90)=1) 

now generate random number between 0 , 1 (like r). have:

f'(x)=r => sin(x)=r => x=arcsin(r) 

actually, need generate random number between 0 , 1 , calculate arcsin of that.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -