Random Number Generator, lower numbers have higher chance

조회 수: 39 (최근 30일)
Nick
Nick 2012년 5월 22일
Hi. I am trying to create a script for generating a random number, with lower numbers having a higher chance of being picked.
This will be in the range of 1 to 20
The percent chance is going to be based on (0.5)^n
So the chance of getting a 1 is 50%, the chance of getting a 2 is 25%, 3 is 12.5% and so on....
I am having trouble getting started with this. I'm not even sure if there is a way. You don't have to write this out, I would just like someone to help me get started or send me in the right direction.

채택된 답변

Walter Roberson
Walter Roberson 2012년 5월 22일
min(ceil(-log2(rand)),20)
  댓글 수: 2
owr
owr 2012년 5월 22일
Thats very nice Walter!
Nick
Nick 2012년 5월 22일
Thanks for this! after looking at it really closely I understand it!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

owr
owr 2012년 5월 22일
If you have a recent version of MATLAB (2012A) and the Statistics Toolbox check out the function "datasample" with the optional parameter 'Weights'.
If not, try using "rand" which generates random numbers uniformly on interval [0,1]. If number is between 0 and 0.5, call it a "1", between 0.5 and 0.75, call it a "2", etc. "histc" should help with this by setting your "edges" to the cumulative sum of your probabilities, ie, 0.5, 0.75, 0.875,...
Thats hwo I would proceed. There might be something pre-built on the file Exchange that does this, or a MATLAB function Im missing.
Good luck.

Stephen
Stephen 2012년 5월 22일
just create the distribution
n=1:20;
dist = [];
for t=1:20
dist = [dist, n(t) * ones(1, round( 20/n(t) ))];
end
then dist(randi(numel(dist))) would give you your weighted answer
you can check hist(dist(randi(numel(dist,1e5,1))),100) to see that the probability is close enough

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by