随机抽样以给出准确的总和

标签 r random sampling

我想对 1000 到 100000 之间的 140 个数字进行采样,这样这 140 个数字的总和约为 200 万(2000000):

sample(1000:100000,140)

使得:
sum(sample(1000:100000,140)) = 2000000

任何指示我如何实现这一目标?

最佳答案

存在一种用于生成此类随机数的算法。

最初为 MATLAB 创建,它有一个 R 实现:

Surrogate::RandVec



引用自 MATLAB 脚本注释:
%   This generates an n by m array x, each of whose m columns
% contains n random values lying in the interval [a,b], but
% subject to the condition that their sum be equal to s.  The
% scalar value s must accordingly satisfy n*a <= s <= n*b.  The
% distribution of values is uniform in the sense that it has the
% conditional probability distribution of a uniform distribution
% over the whole n-cube, given that the sum of the x's is s.
%
%   The scalar v, if requested, returns with the total
% n-1 dimensional volume (content) of the subset satisfying
% this condition.  Consequently if v, considered as a function
% of s and divided by sqrt(n), is integrated with respect to s
% from s = a to s = b, the result would necessarily be the
% n-dimensional volume of the whole cube, namely (b-a)^n.
%
%   This algorithm does no "rejecting" on the sets of x's it
% obtains.  It is designed to generate only those that satisfy all
% the above conditions and to do so with a uniform distribution.
% It accomplishes this by decomposing the space of all possible x
% sets (columns) into n-1 dimensional simplexes.  (Line segments,
% triangles, and tetrahedra, are one-, two-, and three-dimensional
% examples of simplexes, respectively.)  It makes use of three
% different sets of 'rand' variables, one to locate values
% uniformly within each type of simplex, another to randomly
% select representatives of each different type of simplex in
% proportion to their volume, and a third to perform random
% permutations to provide an even distribution of simplex choices
% among like types.  For example, with n equal to 3 and s set at,
% say, 40% of the way from a towards b, there will be 2 different
% types of simplex, in this case triangles, each with its own
% area, and 6 different versions of each from permutations, for
% a total of 12 triangles, and these all fit together to form a
% particular planar non-regular hexagon in 3 dimensions, with v
% returned set equal to the hexagon's area.
%
% Roger Stafford - Jan. 19, 2006

例子:
test <- Surrogate::RandVec(a=1000, b=100000, s=2000000, n=140, m=1, Seed=sample(1:1000, size = 1))
sum(test$RandVecOutput)
# 2000000
hist(test$RandVecOutput)

关于随机抽样以给出准确的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016047/

相关文章:

r - ls 表示交互项的对比

r - 使用grep解析列名

r - 基于属性的 igraph 相邻边

没有重复的Python random.choice方法?

algorithm - bool 网格的随机索引

c - 在超平面上均匀采样

android - 使用RandomAccessFile直接从文件读取时,音频样本中的变化?

c - C中的滚动中值算法

ios - 显示随机启动画面

go - 使用 gonum 进行无放回加权采样