2

Possible Duplicate:
How do you generate a random double uniformly distributed between 0 and 1 from C++?

I'm trying to figure out how to generate a random number between 0 and pi, but the usual method won't work because mod does integer division:

double num = rand() % 2*M_PI;

How would I go about doing this?

Thanks.

Community
  • 1
  • 1
PseudoPsyche
  • 3,964
  • 5
  • 34
  • 55
  • 3
    Have a look at `fmod` in `math.h`, but you might be better off by doing something like `2*M_PI * rand() / (RAND_MAX + 1)`. – Alok Singhal Feb 05 '13 at 17:39
  • I actually saw that before posting this, but wasn't completely sure how it would translate into going to pi. I've got it now. Thanks. – PseudoPsyche Feb 05 '13 at 17:50

1 Answers1

4

Generate a random number between 0 and 1, and then multiply the result by 2*M_PI.

If you have a uniform distribution between 0 and 1, you will also have a uniform distribution between 0 and 2*M_PI, to the limit of precision available in the numeric type you are using.

For generating a random uniform double between 0 and 1, see the answer suggested by @dasblinkenlight in his comment.

andand
  • 16,364
  • 9
  • 51
  • 77
Eric J.
  • 143,945
  • 62
  • 324
  • 540
  • Thanks! Yeah, I saw the thread explaining how to generate a random number between 0 and 1 previously, but didn't realize it was as easy to translate over to pi as simply multiplying. – PseudoPsyche Feb 05 '13 at 17:49