"John Harrison" <john_andronicus@hotmail.com> wrote in message
news:2vol7lF2iq2ieU1@uni-berlin.de...[color=blue]
>
> "Martin" <martin@nospam.com> wrote in message
> news:41971aa8$0$21877$61ce578d@news.syd.swiftdsl.c om.au...[color=green]
>>I am trying to write code that selects a random number in the range 0 to
>>n, where n can be substantially greater than the RAND_MAX on my system
>>which is 32767. I am using VC++ 2003 FWIW.
>> As you know, the standard library rand() only returns an integer in the
>> range 0<=n<=RAND_MAX.
>> In fact, this problem is posed as an exercise by Andrew Koening in
>> Accelerated C++. It's Ex 7-9 and it's marked as "difficult" so I don't
>> feel too bad in asking for help!
>>
>> Is there a standard solution to this? It must be quite a common
>> requirement, but I'm stumped.[/color][/color]
....[color=blue]
> If your range is greater than RAND_MAX then clearly you need to call
> rand() several times. Does that help?
>
> For instance
>
> long big_rand = (RAND_MAX + 1)*(long)rand() + rand();[/color]
Yes. This will work if your randomness requirements are not too high
( which shall be the case anyway if you even consider using std::rand() ).
If the final range is not a power of 2, you may also need to be careful
in the way you map the range (e.g. using a simple division/modulo will
increase the probability of some results compared to others).
See:
http://groups.google.com/groups?thre...ing.google.com
Getting good random numbers is difficult, and gets even harder when
working on security-sensitive applications.
If you feel that you want more than std::rand() can provide, a good
solution might be to consider using another library. I would suggest
taking a look at
http://www.boost.org/libs/random/index.html.
hth,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <>
http://www.brainbench.com