[R] Generating Random Numbers
Petr Savicky
savicky at cs.cas.cz
Thu Jul 19 18:34:21 CEST 2012
On Thu, Jul 19, 2012 at 04:12:07AM -0700, arunkumar1111 wrote:
> hi
>
> My inputs is min=(10,10,10,10,10) and max=(100,100,100,100,100)
> total = 300
> i have to generate 5 numbers between min and max and those numbers should
> sum upto total
Hi.
If we subtract the minimum from each number, then we need to generate
5 numbers from [0, 90], which sum up to 250. The extremal points, which
satisfy these conditions, are all permutations of the vector
90, 90, 70, 0, 0
There are 30 of these permutations. Then, it is sufficient to take
a random convex combination of these points. Try the following.
set.seed(11223344)
# generate all permutations of the vector
u <- c(90, 90, 70, 0, 0)
extremes <- unique(t(replicate(200, u[sample(5)])))
# get a random convex combination
x <- diff(c(0, sort(runif(nrow(extremes)-1)), 1))
out <- c(x %*% extremes + 10)
out
[1] 70.63310 60.11320 67.40902 53.73936 48.10532
sum(out)
[1] 300
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list