# Thread: random number between negative and positive number

1. ## random number between negative and positive number

Hi

I've seen some other threads on this and the faq, but I can't seem to find the answer to this one.

I want to generate a random number (non-integer) between a negative number (such as -1) and a positive number (such as 1). So I want a random number of type double between -1 and 1, how do I do this? Appreciate it if someone could guide me or point me to some useful info. Thank you.

2. Like for example
rand() % 3 - 1

3. anomaly is asking for a non-integer, one way would be:

2.0f * ((float)rand() / (float)RAND_MAX) - 1.0f

4. Hi

Thanks for the example code. Could you also explain the syntax to me? I'm fairly new to c++, so I don't completely understand the syntax yet. Thanks

More specifically, why do you place an 'f' after a number?

5. the function 'rand()' returns a random integer between 0 and RAND_MAX, so to get a random number between 0 and 1 we can use rand() / RAND_MAX since rand() is always less than RAND_MAX, and you know, when using / with integers we get an integer, so we need to convert our integers to double or float first:
(double)rand() / (double)RAND_MAX
Now, this will give us a random between 0 and 1, to get a random number between -1 and 1:

2 * (double)rand() / (double)RAND_MAX - 1

hope you got it now.

f in 2.0f is to tell the compiler that 2.0f is a float and not a double (this would be 2.0)

6. Thanks I already worked out how the code worked before, but thanks for shedding light on the 'f' syntax.

7. np there are also u for unsigned, L for long.