By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,925 Members | 732 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,925 IT Pros & Developers. It's quick & easy.

Random Numbers

P: n/a
In c++ what is the code to make teh program randomly select a number?

Aug 20 '06 #1
Share this Question
Share on Google+
28 Replies


P: n/a
El****@gmail.com wrote:
In c++ what is the code to make teh program randomly select a number?
Usually we employ the help of 'rand' function from the C library.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 20 '06 #2

P: n/a

Victor Bazarov wrote:
El****@gmail.com wrote:
In c++ what is the code to make teh program randomly select a number?

Usually we employ the help of 'rand' function from the C library.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Can you please type out a full line of code

Aug 20 '06 #3

P: n/a
Dirtydog wrote:
Victor Bazarov wrote:
>El****@gmail.com wrote:
>>In c++ what is the code to make teh program randomly select a number?
Usually we employ the help of 'rand' function from the C library.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Can you please type out a full line of code
Please make the effort to learn the language well enough to call a
simple function when you have been given its name. Anybody would think
that Google cost $10 per search by the way you people go on. Are you
really so mentally dull that you can't show any initiative?
Aug 20 '06 #4

P: n/a
On 19 Aug 2006 21:06:11 -0700 in comp.lang.c++, "Dirtydog"
<El****@gmail.comwrote,
>
Can you please type out a full line of code
The usual answer to that is the same in C++ as it is in C, and is
covered in Steve Summit's C FAQ. It is always good to check the FAQ
before posting. You can get the FAQ at:
http://www.eskimo.com/~scs/C-faq/top.html
Aug 20 '06 #5

P: n/a
In c++ what is the code to make teh program randomly select a number?

Effectively, there isn't. rand() has a lot of very bad, bad
properties. It's generally useless for cryptography, for Monte Carlo
simulations, for randomized algorithms, for... etcetera.

If you know that you only need very low-quality random numbers, use
rand(). If you need anything better quality, use your operating
system's built-in facilities (usually CryptGenRandom or /dev/urandom).

Aug 20 '06 #6

P: n/a

Victor Bazarov wrote:
El****@gmail.com wrote:
In c++ what is the code to make teh program randomly select a number?

Usually we employ the help of 'rand' function from the C library.
But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.

Greg

Aug 20 '06 #7

P: n/a
Greg wrote:
>
A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.
If it's available and it doesn't return pseudo-random numbers. It's
allowed to, so check the documentation.
Aug 20 '06 #8

P: n/a
Robert J. Hansen wrote:
>>In c++ what is the code to make teh program randomly select a number?


Effectively, there isn't. rand() has a lot of very bad, bad
properties.
Where in the standard is this requirement? <g>

Many years ago, there were many bad implementations of rand. There still
may be.
Aug 20 '06 #9

P: n/a

<El****@gmail.comwrote:
In c++ what is the code to make the program randomly select a number?
Here's some functions I wrote a while back to get decent pseudo-random
integers and doubles:

First, to seed the random number generator by time (which makes the
pseudo-random numbers less repeatable, and hence less "pseudo"), run
THIS function *ONCE ONLY* at the beginning of your main():

#include <cmath>
inline void Randomize(void)
{
srand(time(0));
}

Now a function to get a pseudo-random double within a given range:

// Get random double:
inline double RandNum(double min, double max)
{
return min + (max - min) * (
static_cast<double>(rand())
/
static_cast<double>(RAND_MAX)
);
}

And finally, a function to get a pseudo-random integer within a given range:

// Get random int:
inline int RandInt(int min, int max)
{
return static_cast<int>(RandNum(min + 0.001, max + 0.999));
}

If you're wondering about the 0.001 and 0.999, they're necessary to prevent
two different kinds of error:

1. Fencepost errors. If you don't carfully skew the end points, the minimum
and maximum integers of your range will have dramatically different
probability of occurring than any of the other integers in the range.
For example, to get equal probabilities for the interval [5,9], you
need to feed min=5.001, max=9.999 to RandNum. Thus the range of
doubles corresponding to 9 is about 1. (If you had fed the more
intuitive value of 9.000 to RandNum, then 9's probability would
be 0.000%, not 20.000% as it should be.)

2. Roundoff errors. When casting back and forth between double and int,
it's easy to accidentally end up with a number that's 1 less or more
than it should be. Hence I add a saftey margin of 0.001.

--
Cheers,
Robbie Hatley
East Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
home dot pac bell dot net slant earnur slant
Aug 20 '06 #10

P: n/a
Robbie Hatley wrote:
>
// Get random double:
inline double RandNum(double min, double max)
{
return min + (max - min) * (
static_cast<double>(rand())
/
static_cast<double>(RAND_MAX)
change that last bit to (static_cast<double>(RAND_MAX) + 1). RAND_MAX is
the maximum value that rand() will return. As written, RandNum returns
max only when rand() returns RAND_MAX. Other values come up more often.
);
}

And finally, a function to get a pseudo-random integer within a given range:

// Get random int:
inline int RandInt(int min, int max)
{
return static_cast<int>(RandNum(min + 0.001, max + 0.999));
}

If you're wondering about the 0.001 and 0.999, they're necessary to prevent
two different kinds of error:

1. Fencepost errors. If you don't carfully skew the end points, the minimum
and maximum integers of your range will have dramatically different
probability of occurring than any of the other integers in the range.
Only if the floating-point values that you're working with are skewed.
With the change I suggested above, removing the adjustments here will
produce values in the half-open interval [min,max] that are as well
distributed as the values returned by rand().
Aug 20 '06 #11

P: n/a
Greg posted:
But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.

While we're being pedantic -- there's no such thing as a random number.

--

Frederick Gotham
Aug 20 '06 #12

P: n/a
Robbie Hatley posted:
inline double RandNum(double min, double max)
{
return min + (max - min) * (
static_cast<double>(rand())
/
static_cast<double>(RAND_MAX)
);
}

The twin casts are slight overkill (in my opinion):

inline
double RandNum(double const min,double const max)
{
return (max-min) * rand() / (RAND_MAX+1) + min;
}

Or, if you would prefer the division to take place before the multiplication:

return (max-min) * (rand() / (double)(RAND_MAX+1)) + min;

--

Frederick Gotham
Aug 20 '06 #13

P: n/a
In article <9h*******************@news.indigo.ie>,
Frederick Gotham <fg*******@SPAM.comwrote:
>Greg posted:
>But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.

While we're being pedantic -- there's no such thing as a random number.
17 is my personal favorite. :)
--
Greg Comeau / 20 years of Comeauity! Intel Mac Port now in alpha!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 20 '06 #14

P: n/a
In article <9h*******************@news.indigo.ie>, fg*******@SPAM.com
says...

[ ... ]
While we're being pedantic -- there's no such thing as a random number.
This is mostly a question of how you define your terms. At least IMO,
however, as an unqualified statement, it's false. There are things such
as radioactive decay that, at least with our current knowledge of
physics, are completely unpredictable. When done properly, masurements
of such things can produce, for example, a series of bits that is
"random" for any practical definition of the term -- i.e. nobody seems
to have found a way to predict the next bit that will be produced with
any better than 50% accuracy -- i.e. random chance.

Beyond that, what you choose to say about things is mostly a question of
how you prefer to define your terms.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 20 '06 #15

P: n/a
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.comwrote:
>In article <9h*******************@news.indigo.ie>, fg*******@SPAM.com
says...

[ ... ]
>While we're being pedantic -- there's no such thing as a random number.

This is mostly a question of how you define your terms. At least IMO,
however, as an unqualified statement, it's false. There are things such
as radioactive decay that, at least with our current knowledge of
physics, are completely unpredictable. When done properly, masurements
of such things can produce, for example, a series of bits that is
"random" for any practical definition of the term -- i.e. nobody seems
to have found a way to predict the next bit that will be produced with
any better than 50% accuracy -- i.e. random chance.

Beyond that, what you choose to say about things is mostly a question of
how you prefer to define your terms.
IOWs, random is random :)
--
Greg Comeau / 20 years of Comeauity! Intel Mac Port now in alpha!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 20 '06 #16

P: n/a
Frederick Gotham wrote:
Greg posted:
>But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.


While we're being pedantic -- there's no such thing as a random number.
Sure there is, for instance 2. <g>
Best

Kai-Uwe Bux
Aug 20 '06 #17

P: n/a
Kai-Uwe Bux posted:
Frederick Gotham wrote:
>Greg posted:
>>But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.


While we're being pedantic -- there's no such thing as a random number.

Sure there is, for instance 2. <g>

When the Big Bang occurred, molecules and atoms and so forth got flung out in
ever direction -- the resultant collisions and changes in trajectory resulted
in the formation of you as an organism, and resulted in your choice of 2.

So you see, it wasn't random. ;)

--

Frederick Gotham
Aug 20 '06 #18

P: n/a
Frederick Gotham wrote:
Kai-Uwe Bux posted:
>Frederick Gotham wrote:
>>Greg posted:

But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.
While we're being pedantic -- there's no such thing as a random number.

Sure there is, for instance 2. <g>


When the Big Bang occurred, molecules and atoms and so forth got flung out
in ever direction -- the resultant collisions and changes in trajectory
resulted in the formation of you as an organism, and resulted in your
choice of 2.

So you see, it wasn't random. ;)
If you want to choose a random order of a deck of cards, then you could
shuffle the deck and put down all cards in order, or you could shuffle,
remove a card and put it down, shuffle again, put down a card, shuffle,
put, ... until all cards are put down. Both procedures are strictly
equivalent. In other words: there is no difference between a sequence of
random events and a determined destiny chosen randomly in the beginning. In
a deterministic universe, the big bang just chose a destiny for the world,
but it may have done so randomly.
Best

Kai-Uwe Bux
Aug 20 '06 #19

P: n/a
Frederick Gotham wrote:
Kai-Uwe Bux posted:
>Frederick Gotham wrote:
>>While we're being pedantic -- there's no such thing as a random
number.

Sure there is, for instance 2. <g>


When the Big Bang occurred, molecules and atoms and so forth got flung
out in ever direction -- the resultant collisions and changes in
trajectory resulted in the formation of you as an organism, and
resulted in your choice of 2.
Yes, but only in _this_ universe ;)
So you see, it wasn't random. ;)
Aug 20 '06 #20

P: n/a
Frederick Gotham wrote:
Kai-Uwe Bux posted:
>Frederick Gotham wrote:
>>Greg posted:

But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.

A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available for
your compiler) would provide an actual random number.

While we're being pedantic -- there's no such thing as a random number.
Sure there is, for instance 2. <g>


When the Big Bang occurred, molecules and atoms and so forth got flung out in
ever direction -- the resultant collisions and changes in trajectory resulted
in the formation of you as an organism, and resulted in your choice of 2.

So you see, it wasn't random. ;)
You assume that this is the only universe, and that there isn't some
universe somewhere where he chose a different number :)
--
Clark S. Cox III
cl*******@gmail.com
Aug 20 '06 #21

P: n/a
Clark S. Cox III wrote:
Frederick Gotham wrote:
>Kai-Uwe Bux posted:
>>Frederick Gotham wrote:

Greg posted:

But rand() returns a "pseudo-random" number. Each number returned
depends on the previous one. The entire sequence that rand() returns
only appears to be random. In reality the series is deterministic and
will start to repeat itself after rand() has been called enough times.
>
A truly random number would have to obtained in a non-deterministic
way. In that case std::tr1::random_device (assuming it is available
for your compiler) would provide an actual random number.

While we're being pedantic -- there's no such thing as a random number.
Sure there is, for instance 2. <g>


When the Big Bang occurred, molecules and atoms and so forth got flung
out in ever direction -- the resultant collisions and changes in
trajectory resulted in the formation of you as an organism, and resulted
in your choice of 2.

So you see, it wasn't random. ;)

You assume that this is the only universe, and that there isn't some
universe somewhere where he chose a different number :)
Pardon me,
whoever in that alternate universe chose that different number sure wasn't
me. (I would know :)
Best

Kai-Uwe Bux
Aug 20 '06 #22

P: n/a
Frederick Gotham wrote:
While we're being pedantic -- there's no such thing as a random number.
While you'll always get some determinism from your measuring apparatus,
radioisotope decay is random enough for virtually any purpose. Many
crypto accelerator cards nowadays use radioisotope decay for their
built-in RNGs.

Aug 21 '06 #23

P: n/a
Frederick Gotham wrote:
Robbie Hatley posted:
> inline double RandNum(double min, double max)
{
return min + (max - min) * (
static_cast<double>(rand())
/
static_cast<double>(RAND_MAX)
);
}


The twin casts are slight overkill (in my opinion):

inline
double RandNum(double const min,double const max)
{
return (max-min) * rand() / (RAND_MAX+1) + min;
}

Or, if you would prefer the division to take place before the multiplication:

return (max-min) * (rand() / (double)(RAND_MAX+1)) + min;
There exists good books about random numbers.

A well know book is "Numerical Recipes" which is free of charge on the
Internet and has implemented algorithms. There exists an chapter only
for random numbers and it explains very well the theory.

Besides discussing, you can go and read the book for a better view of
what is a random number.

--
Posted via a free Usenet account from http://www.teranews.com

Aug 21 '06 #24

P: n/a
Frederick Gotham wrote:
>
When the Big Bang occurred, molecules and atoms and so forth got flung out in
ever direction -- the resultant collisions and changes in trajectory resulted
in the formation of you as an organism, and resulted in your choice of 2.

So you see, it wasn't random. ;)
Although I see that the discussion is gowing in the direction of fun, I
would like to point out that the evolution is not entirely determined by
it's initial state.
This is what quantum theory told us and which opposes to the view of
physics at the end of the 19th century when people thought that
everything can be predicted when the initial state is know precisely
enough...

So yes there exists (at the present knowledge) am experiment which can
yield a true random number.

Phil
Aug 21 '06 #25

P: n/a
In article <ec**********@panix1.panix.com>, co****@panix.com says...

[ ... ]
Beyond that, what you choose to say about things is mostly a question of
how you prefer to define your terms.

IOWs, random is random :)
More completely, "random as far as we can tell" is random.

Somebody who chooses to do so can argue that a deity or perhaps another
race somewhere else in the universe might be able to predict things like
radioactive decay with perfect accuracy -- and I'm certainly not in a
position to disprove that possibility. At the same time, until or unless
WE can figure out how to do so, such a sequence is random for any
practical purpose.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 21 '06 #26

P: n/a

"Pete Becker" <pe********@acm.orgwrote in message
news:Qe******************************@giganews.com ...
Robert J. Hansen wrote:
>>>In c++ what is the code to make teh program randomly select a number?


Effectively, there isn't. rand() has a lot of very bad, bad
properties.

Where in the standard is this requirement? <g>
Well, there isn't and that might be the source of the problem. On the other
hand the question arises whether it is the business of a language-standard
to require certain quality levels for a RNG?
Many years ago, there were many bad implementations of rand. There still
may be.
Oh there certainly are. However, there is also a plethora of non rand() RNGs
which one should better send to /dev/nul.

Cheers
Chris
Aug 21 '06 #27

P: n/a

El****@gmail.com wrote:
In c++ what is the code to make teh program randomly select a number?
with randomaize(). and random

Aug 21 '06 #28

P: n/a

<rp**********@gmail.comwrote in message
news:11*********************@i3g2000cwc.googlegrou ps.com...
>
El****@gmail.com wrote:
>In c++ what is the code to make teh program randomly select a number?
with randomaize(). and random
Umm... what?

There are no such functions. Perhaps you mean srand() and rand()?

-Howard
Aug 21 '06 #29

This discussion thread is closed

Replies have been disabled for this discussion.