473,788 Members | 2,828 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Easy random numbers?

I'm a newbie at C++, but no stranger to other programming languages. I'm
working on my first C++ program (besides "hello world" and the like),
and it needs to generate a (pseudo-)random number between 1 and 10. What
would be the simplest way to do that? All of the libraries I found on
Google seemed to be made for rocket scientists.
Jul 19 '05 #1
7 10524
In comp.lang.c++
Leif K-Brooks <eu************ ******@ec.REMOV E.ritters.biz> wrote:
I'm a newbie at C++, but no stranger to other programming languages. I'm
working on my first C++ program (besides "hello world" and the like),
and it needs to generate a (pseudo-)random number between 1 and 10. What
would be the simplest way to do that? All of the libraries I found on
Google seemed to be made for rocket scientists.


Why not use the standard function in every C++ compiler called, rand()?
Jul 19 '05 #2
Bruce wrote:
Why not use the standard function in every C++ compiler called, rand()?


Thanks, that's just what I was looking for.
Jul 19 '05 #3
>> Why not use the standard function in every C++ compiler called, rand()?

Thanks, that's just what I was looking for.


note that you should call srand() first, to seed the RNG. The typical
(not especially good) method is

srand(time(NULL ));

On *nix, this is somewhat better:

srand(time(NULL ) ^ getpid());

-Dave
Jul 19 '05 #4
In article <Uf************ ****@fe01.atl2. webusenet.com>,
Leif K-Brooks <eu************ ******@ec.REMOV E.ritters.biz> wrote:
and it needs to generate a (pseudo-)random number between 1 and 10. What
would be the simplest way to do that?


The simplest way is to use the functions in the C++ standard library:

#include <iostream>
#include <cstdlib>

using namespace std;

int main ()
{
const int seed = 29325; // or anything else you like
const int maxrand = 10;
srand (seed);
for (int k = 0; k < 20; ++k)
{
int x = (rand() % maxrand) + 1;
cout << x << endl;
}
return 0;
}

Note that this may not give you very good random numbers, depending on the
implementation that comes with your compiler. For simple uses it will
probably suffice, but for sophisticated Monte-Carlo simulations where
quality of randomness is important, you should upgrade to something better
before you do serious analysis.

When I was a graduate student, one of my friends started getting results
that seemed to indicate the existence of a previously-unknown elementary
particle. After two weeks of checking, he found out it was a flaw in his
random number generator. No Nobel Prize for him! :-(
--
Jon Bell <jt*******@pres by.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 19 '05 #5
Jon> int main ()
Jon> {
Jon> const int seed = 29325; // or anything else you like
Jon> const int maxrand = 10;
Jon> srand (seed);
Jon> for (int k = 0; k < 20; ++k)
Jon> {
Jon> int x = (rand() % maxrand) + 1;
Jon> cout << x << endl;
Jon> }
Jon> return 0;
Jon> }

Jon> Note that this may not give you very good random numbers,
Jon> depending on the implementation that comes with your compiler.

I can make a stronger statement than that -- in general, this technique
*will* not give you very good random numbers, regardless how good the
implementation is that comes with your compiler. Moreover, the larger
maxrand is, the worse the random numbers will be.

Here's why. The built-in rand function is not required to yield random
numbers larger than 32767. Suppose, for the sake of argument, that this
particular implementation does limit its random numbers to 0<=n<=32767,
and that instead of maxrand being 10, it is 10,000. Then:

if rand() yields then x will be

0 <= rand() < 10000 0
10000 <= rand() <= 20000 1
20000 <= rand() <= 30000 2
30000 <= rand() <= 32767 0

You will see that 0 will show up substantially more often than 1 or 2.

Here is an implementation of a function that does a better job:

// return a random integer r such that 0 <= r < n.
int nrand(int n)
{
assert (n <= 0 || n > RAND_MAX);

const int bucket_size = RAND_MAX / n;
int r;

do r = rand() / bucket_size;
while (r >= n);

return r;
}

For more information, please see page 135 in ``Accelerated C++.''
--
Andrew Koenig, ar*@acm.org
Jul 19 '05 #6
Andrew Koenig wrote in news:yu******** ******@tinker.r esearch.att.com :
Jon> for (int k = 0; k < 20; ++k)
Jon> {
Jon> int x = (rand() % maxrand) + 1;
Jon> cout << x << endl;
Jon> }
Jon> return 0;
Jon> }

Jon> Note that this may not give you very good random numbers,
Jon> depending on the implementation that comes with your compiler.

I can make a stronger statement than that -- in general, this
technique *will* not give you very good random numbers, regardless how
good the implementation is that comes with your compiler. Moreover,
the larger maxrand is, the worse the random numbers will be.

Here's why. The built-in rand function is not required to yield
random numbers larger than 32767. Suppose, for the sake of argument,
that this particular implementation does limit its random numbers to
0<=n<=32767, and that instead of maxrand being 10, it is 10,000.
Then:

if rand() yields then x will be

0 <= rand() < 10000 0
10000 <= rand() <= 20000 1
20000 <= rand() <= 30000 2
30000 <= rand() <= 32767 0

You will see that 0 will show up substantially more often than 1 or 2.


I think you mixed up you're tables for operator / with those for
operator %.

equation is x = (rand() % maxrand) + 1;
maxrand is 10000.

if rand() yields then x will be

0 <= rand() < 10000 rand() + 1
10000 <= rand() <= 20000 rand() - 10000 + 1
20000 <= rand() <= 30000 rand() - 20000 + 1
30000 <= rand() <= 32767 rand() - 30000 + 1

the 4th set gives a range of [1, 2768] all the others give a range
of [1, 10000].

This lead's to values in the range [1, 2768] being more likely
than values in the range [2769, 10000].

probability in [1, 2768] = 4 / 32768.0 and
probability in [2769, 10000] = 3 / 32768.0

If maxrange = 10 then we have (RAND_MAX) % 10 == 7 and
(RAND_MAX / 10 == 3276 so we get:

probability in [1, 8] = (3276 + 1) / 32768.0 and
probability in [9, 10] = 3276 / 32768.0

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #7
Rob> I think you mixed up you're tables for operator / with those for
Rob> operator %.

You're quite right. However, the conclusion is still correct: Using
rand()%n to compute random numbers in the range [0, n) usually gives a
nonuniform distribution, and the distribution becomes less uniform as
n increases.

--
Andrew Koenig, ar*@acm.org
Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
11961
by: Nicholas Geraldi | last post by:
Im looking for a decent random number generator. Im looking to make a large number of random numbers (100 or so, if not more) in a short period of time (as fast as possible). the function i was using to get random numbers was Random rn = new Random(System.currentTimeMillis()); but it seems that the system doesn't update the milliseconds often enough to cause a true randomaziation (i ran just the System.currentTimeMillis() in a
21
3025
by: Marc Dansereau | last post by:
Hi all I am new to this forum and to the c programming language. If I understand, the random() function in C return numbers that follow a uniform distribution U(0,1). Can somebody know how to generate a set of random number that follow a normal distribution N(0,1) ? I am develloping on power4 machine running AIX. Thank you for your help
5
2401
by: cvnweb | last post by:
I am trying to generate 2 random numbers that are diffrent, in order to add them to existing numbers to generate numbers that start out the same, but are randomly added and subtracted so that they can go down similar paths, but not be the same. I will implement code later to make sure i they go more than 10 apart from each other that they are moved closer together, but this is what I have so far, and when the program is run, the two random...
104
5194
by: fieldfallow | last post by:
Hello all, Is there a function in the standard C library which returns a prime number which is also pseudo-random? Assuming there isn't, as it appears from the docs that I have, is there a better way than to fill an array of range 0... RAND_MAX with pre-computed primes and using the output of rand() to index into it to extract a random prime.
12
5231
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's RAND(). any ideas? I suppose I could use the current rancom number as the seed for the next random number. but would that really work?
6
1382
by: BurnTard | last post by:
I can hardly solve the simplest thing without asking thescripts for help... Must be getting late. If I keep this up, I'll be an admin within the month. This time, I have a list with six random numbers in it. Since the numbers are random, I don't know at which indexes they are. What I want to do is basically: str= "" str=raw_input("Random gibberish") a= if str in a: print "Random gibberish"
13
2815
by: Peter Oliphant | last post by:
I would like to be able to create a random number generator that produces evenly distributed random numbers up to given number. For example, I would like to pick a random number less than 100000, or between 0 and 99999 (inclusive). Further, the I want the range to be a variable. Concretely, I would like to create the following method: unsigned long Random( unsigned long num )
6
11753
by: badcrusher10 | last post by:
Hello. I'm having trouble figuring out what to do and how to do.. could someone explain to me what I need to do in order to work? THIS IS WHAT I NEED TO DO: Professor Snoop wants a program that will randomly generate 10 unique random numbers. Your job is to write a program that produces random permutations of the numbers 1 to 10. “Permutation” is a mathematical name for an arrangement. For example, there are six permutations of the...
24
7235
by: pereges | last post by:
I need to generate two uniform random numbers between 0 and 1 in C ? How to do it ? I looked into rand function where you need to #define RAND_MAX as 1 but will this rand function give me uniformly distributed and unique numbers ?
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10175
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3675
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.