Is there a fast way to do that?
+1
A:
I suppose you could do this with rand:
for (int i = 0; i < M; i++)
{
v.push_back(rand()%(2*K)-K;
}
But I need to know more about your question. Is the interval [-K,K] or (-K,K)? Do you include -K and K or not?
JoshD
2010-09-30 05:37:26
Using modulus biases the result, if the size of the output interval does not evenly divide `RAND_MAX`.
caf
2010-09-30 05:38:23
Yes, that is true. Keep that in mind, neversaint. For smaller K it will be less biased, but when you get closer to the max value for rand, you'll really mess things up!
JoshD
2010-09-30 05:41:22
Minor point, but you may want to v.reserve( M ); before the loop, so the vector doesn't realloc over and over until it is big enough. (which in most cases the capacity will have grown to larger than M)
KSchmidt
2010-09-30 05:41:52
@JoshD: Thanks. Yes -K and K in included.
neversaint
2010-09-30 05:42:38
And `rand` is often a horrible random number generator. Don't use it.
Turtle
2010-09-30 05:43:23
@KSchmidt: Another good point. (Though I didn't even declare v :) ). This will save you log(M) reallocations, which is always a good decision!
JoshD
2010-09-30 05:43:36
@Turtle: it might be suitable if he isn't using this for sensitive stuff. He did say quickly... I wish he'd give more details, though.
JoshD
2010-09-30 05:46:45
@caf/JoshD: if someone cared, easy to do something like `max = INT_MAX / K * K; for (...) { while ((r = rand()) >= MAX) /* nop */; v.push_back(r % (2*k) - k); }`
Tony
2010-09-30 07:45:29
+4
A:
I would recommend using the Mersenne Twister to generate uniform random variables. If you generate a uniform deviate u ~ [0,1] then (2 * K) * u - K will be ~ [-K, K].
M. Tibbits
2010-09-30 05:38:00