Random Number Generator, lower numbers have higher chance
조회 수: 22 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
추가 답변 (2개)
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.
댓글 수: 0
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!