tags:

views:

119

answers:

4

We know that to generate random long number we do following steps in Java

Random r=new Random()
 return r.nextLong();

what will be equivalent of this code in C++? like this?

return (long) rand();
+2  A: 

Portable hack:

long r = 0;
for (int i = 0; i < sizeof(long)/sizeof(int); i++)
{
    r = r << (sizeof(int) * CHAR_BITS);
    r |= rand();
}
return r;

Why do you need a random long anyway?

Uli Schlachter
It is not a good idea in Visual Studio, RAND_MAX is 2^15-1 and many bits will be 0 in the final number.
jbernadas
To be perfectly portable, always use `CHAR_BITS`, instead of the literal `8`.
sbi
Are you sure of the quality of random numbers you're getting this way?
Zhenya
There aren't any systems today where CHAR_BITS is not 8, but sure. And the quality of random numbers from rand() isn't very good anyway. If one makes sure to avoid those 0 bits portably, we'd need floor(log_2(RAND_MAX)) and only use that many bits of the return value. Depending on the requirements, this might be a little overkill.
Uli Schlachter
@Uli Schlachter: Doing Monte Carlo similations for a sizable fraction of my work time, I've seen quite a few disasters where the problem was really due to a bad random number generator or a "simple" hack of it. Frankly, I'd say that what you're suggesting is a step too close to a big no-no.
Zhenya
+9  A: 

Using boost random library can save you of quite nasty surprises with (pseudo)random numbers

Zhenya
"Use boost to solve <*> problem" became a standard answer on any type of question :P.
virious
@virious: I don't know of "any question". Here it's all about an algorithm. Sure, you can code your own version of Mersenne Twister, or summon hard-to-find bugs by hacking the standard rand() --- or use boost::random, which is, like, three lines of code.
Zhenya
@Zhenya: it was just my feeling, in general, not in case of your particular answer :). Yes, it's obvious that boost is a very well optimized set of libraries which is used very often.
virious
+5  A: 

First, you have ton know that in the current standard C++ there is no random library. In fact there is one, but it's available in a sperate namespace called TR1 because it's the result of a Technical Report done in 2003. It will be available in the standard library for the next standard (coming next year if all goes well).

So if you have a recent compiler (VS2008 or lasts versions of GCC) you have access to the std::tr1::random library; If you have a compiler implementing the parts of the next standard, then you have it std::random.

If you don't have access to that library, there is an implementation available in the boost libraries : http://www.boost.org/doc/libs/1_44_0/doc/html/boost_random.html

Now in all cases, the way to get a random number is the same as it's all the same library (from the boost doc):

boost::mt19937 rng;                 // produces randomness out of thin air
                                    // see pseudo-random number generators
boost::uniform_int<> six(1,6);      // distribution that maps to 1..6
                                    // see random number distributions
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
         die(rng, six);             // glues randomness with mapping
int x = die();                      // simulate rolling a die
Klaim
Wouldn't `using namespace boost::random;` put all of `boost::random` into the _current_ namespace? How then would the compiler find it in `boost`? What am I missing?
sbi
@sbi: using makes it available in both.@Klaim: what about cstdlib?
Tony
@Tony: I don't see how this is supposed to happen. Care to elaborate?
sbi
@sbi: say you #include <string> / using namespace std; - afterwards string and std::string can both be used interchangeably... they refer to the same thing. using grants a kind of liberty to the compiler to look somewhere extra implicitly, but it doesn't move things from their original namespace. Is that clearer?
Tony
@Tony: Well, [I do know a few basics of C++](http://stackoverflow.com/badges/49/c?userid=140719). `<wry_smile>` However, I still fail to see how using namespace boost::random; (as was in the original version of Klaim's answer) puts everything from boost::random into boost (unless the using directive is put into boost, of course, which it wasn't).
sbi
I added first using boost::random to the example, thinking there was a missing line in the example of the doc. But it's not a mistake, so I fixed it. See the first page of the doc.
Klaim
+2  A: 

<cstdlib> provides int rand(). You might want to check out the man page. If long is bigger than int on your system, you can call rand() twice and put the first value in the high word.

#include <cstdlib>

long lrand()
{
    if (sizeof(int) < sizeof(long))
        return (rand() << (sizeof(int) * 8)) | rand();
    return rand();
}

(it's very unlikely that long is neither the same as or double the size of int, so this is practical if not theoretically perfect)

Check your docs for rand() though. It's not a great generator, but good enough for most things. You'll want to call srand() to initialise the random-number generation system. Others have commented that Windows doesn't return sizeof(int) randomised bits, so you may need to tweak the above.

Tony