rand()

This is a discussion on rand() within the C Programming forums, part of the General Programming Boards category; Hello, We try to generate a random number between 0 and 1. Does anyone know how? Thanks!...

1. rand()

Hello,

We try to generate a random number between 0 and 1.
Does anyone know how?

Thanks!

2. Yes.

Edit: Salem pointed this out recently in another thread:
http://www.catb.org/~esr/faqs/smart-...ons.html#prune
--
Mats

3. Thanks Dino, but it doesn't specify how to make the number in the range 0 to 1.

Matsp, If anyone knows how to generate a random number between 0 and 1 please help us (is this an English forum?)

4. Do some math!!

1) Figure out what RAND_MAX is.
2) cast the returned value as a double
3) divide #2 by #1 above

5. Originally Posted by Livnat
Matsp, If anyone knows how to generate a random number between 0 and 1 please help us (is this an English forum?)
So, have a look at the link I posted: Ask smart questions, unless you want smart-ass answers. Yes, I know how to do that.

So what have you tried so far?
Do you want an integer value (one or zero) or a floating point in the range 0.0 - 1.0 or 0.0 - 0.99999999... ?

--
Mats

6. More generally, I suggest that you read Prelude's article on using rand().

7. The typical solution for this is to use C and C++'s remainder operator to force the range down to whatever is desired. For example, to shrink the range into [0..N), one might do this:
Code:
`int r = rand() % N;`

8. Originally Posted by blurx
...to shrink the range into [0..N),...
My my, proper range notation. I'm impressed!!

9. Originally Posted by Dino
My my, proper range notation. I'm impressed!!
I just copied off that off the link that laserlight gave.

10. >I'm impressed!!
I get "it's" and "its" right most of the time too. How's that for impressive?

11. Wow.