# rand() in decimals.

• 10-14-2007
DarrenY
rand() in decimals.
Hi, I'm wondering how do I generate random numbers in decimals?
Meaning between 0-1.

Any ideas? rand() returns from the minimum of 1.
• 10-14-2007
laserlight
Read Prelude's article on Using rand(), in particular about creating a uniform deviate.
• 10-14-2007
DarrenY
Thanks for the link, my mind must've slipped as this could also be done.

Code:

```      float k = (rand()%10);       k = k/10;```
• 10-14-2007
Prelude
>float k = (rand()%10);
>k = k/10;
Apparently you didn't read the entire article. :P
• 10-14-2007
Yarin
I've always done it like so:
Code:

```float frand(int chop, int perk = 10) {   return (float(rand() &#37; chop) * pow(10.0, float(perk))) / pow(10.0, float(perk));  }```
• 10-14-2007
matsp
Quote:

Originally Posted by Yarin
I've always done it like so:
Code:

```float frand(int chop, int perk = 10) {   return (float(rand() % chop) * pow(10.0, float(perk))) / pow(10.0, float(perk));  }```

You probably want to read (and understand) Prelude's page too - that is, if you care about the distribution of your random numbers. [And if you REALLY want good random numbers, don't use rand - as it's by no means guaranteed to be "good"].

--
Mats
• 10-14-2007
Yarin
I did read it quite a while ago, but I figured out that rand() was producing pretty much the same thing as her version of rand(). All I have to do is call srand() every 1k calls to rand().
• 10-14-2007
matsp
Quote:

Originally Posted by Yarin
I did read it quite a while ago, but I figured out that rand() was producing pretty much the same thing as her version of rand(). All I have to do is call srand() every 1k calls to rand().

Calling srand again after calling it the first time will NOT improve the distribution of your sequence - it will restart the sequence with a different seed, and depending on the seed value, it may give you the same sequence as last time or a different sequence. But it won't make the distribution any better.

--
Mats