tags:

views:

60

answers:

2

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
Using modulus biases the result, if the size of the output interval does not evenly divide `RAND_MAX`.
caf
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
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
@JoshD: Thanks. Yes -K and K in included.
neversaint
And `rand` is often a horrible random number generator. Don't use it.
Turtle
@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
@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
@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
+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
I think some uniformed deviates go to the private school near here.
caf