3

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
  • 4,332
  • 5
  • 37
  • 58
  • 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
  • Why is C-related questions closed with C++-related duplicate? The question is still here: how to get uniform distributed double/float value in *[0, 1)*. – Stanislav Volodarskiy Jul 01 '23 at 22:06

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
  • 17,134
  • 11
  • 53
  • 79
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • 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