フィルターのクリア

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 Center および File ExchangeCalendar についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by