Rounded random numbers with fixed sum

19 ビュー (過去 30 日間)
Thomas Coppin
Thomas Coppin 2020 年 8 月 10 日
コメント済み: Thomas Coppin 2020 年 8 月 10 日
I'm trying to generate a 1xK array with 'random' numbers that sum to 1, but that are also rounded to either 1 or 2 decimal places.
For example, if K=3, and I want the numbers to 2 decimal places, this is what I would expect:
array = [0.27, 0.45, 0.27].
So far I am unable to achieve this. Here is my code.
K = 3;
r = rand(1,K);
r = round(r/sum(r),2);
Without rounding the numbers sum to 1, but once rounded the numbers only to sum to 1 approximately 50% of the time.
Any help would be greatly appreciated, thanks!
  2 件のコメント
madhan ravi
madhan ravi 2020 年 8 月 10 日
sum(array) is not exactly one?
Thomas Coppin
Thomas Coppin 2020 年 8 月 10 日
No, once you round the values (after dividing by the sum) they no longer sum to exactly one.

サインインしてコメントする。

回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 8 月 10 日
編集済み: Walter Roberson 2020 年 8 月 10 日
Multiply your desired total by 10 to the number of digits you need. Generate using Roger's code. Divide everything by 10 to the number of digits you need.
The sum of these will not in general be exactly the required value due to round off when adding floating-point numbers. In the test I just did of 1000 integers from 1 to 999, sum(v) /10 was different than sum(v/10) by 2*eps() of the value.

Bruno Luong
Bruno Luong 2020 年 8 月 10 日
k = 3;
r = (diff([0 sort(randperm(100+k-1,k-1)) 100+k])-1)/100
  4 件のコメント
Bruno Luong
Bruno Luong 2020 年 8 月 10 日
編集済み: Bruno Luong 2020 年 8 月 10 日
No but you can use Roger's RANDFIXEDSUM
k = 3;
x = round([0; cumsum(randfixedsum(k, 1, 100, 0, 0.5*100))]);
x(end) = 100; % prevent floating point error
r = diff(x')/100
The distribution might be not perfectly uniform but possibly close enough and suitable for what ever you want to do with it.
Thomas Coppin
Thomas Coppin 2020 年 8 月 10 日
Thanks Bruno, that does exactly what I require.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by