-4

Using C Language:

  • How can I generate random numbers in the [pi, 2pi] range?
  • How can I generate random numbers in the [-1, 0] range?
user3482381
  • 83
  • 1
  • 7
  • 5
    Did you read documentation for rand()? – Adriano Repetti Apr 08 '14 at 15:54
  • 1
    possible duplicate of [How to generate a random number from within a range](http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range) – StephenTG Apr 08 '14 at 15:55
  • I have read the documentation of rand(). I think that the answer of the second quastion is `x = rand()/RAN_MAX -1`, but I don't know how to implement the range [pi, 2pi]. – user3482381 Apr 08 '14 at 18:59

1 Answers1

1

This is a pseudo random integer generator, but has only been tested for positive numbers, you would have to modify it to use with negatives:

int randomGenerator(int min, int max)
{
    int random=0, trying=0;

    trying = 1;         
    srand(clock());
    while(trying)
    {
        random = (rand()/32767.0)*(max+1);
        (random >= min) ? (trying = 0) : (trying = 1);
    }

    return random;
}

EDIT (last method did not produce randoms due to srand() not being updated enough)

For a range spanning positive and negative numbers you could modify it like this: (but ratio of pos to neg would be same)

int randomGenerator(int min, int max)
{
    int random=0, trying=0;
    int i=0;

    trying = 1;

    srand(clock());
    while(trying)
    {

        random = (rand()/32767.0)*(max+1);
        (random >= min) ? (trying = 0) : (trying = 1);
    }

    return (i++%2==0)?(random):(-1*random);
}
ryyker
  • 22,849
  • 3
  • 43
  • 87