473,837 Members | 1,624 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Random number if range is greater than RAND_MAX?

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.

Thanks,
Martin
Jul 22 '05 #1
9 10602

"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.

Thanks,
Martin


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();

john
Jul 22 '05 #2
"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2v******** *****@uni-berlin.de...

"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.
.... 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();


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
Jul 22 '05 #3

"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.

Thanks,
Martin


Assume N < LONG_MAX is your upper limit. I would generate a random (double)
number between 0 and 1, then multiply by N and store it in a long. Untested
code:

#include <stdlib.h>

const long N = 987654321; /* upper limit */

int main(void) {
double d;
long result;
srand((unsigned ) time(NULL));
d = rand() / RAND_MAX;
result = d * N;
}
Jul 22 '05 #4

"Method Man" <a@b.c> wrote in message
news:kD******** ************@re ad2.cgocable.ne t...

"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.

Thanks,
Martin


Assume N < LONG_MAX is your upper limit. I would generate a random
(double)
number between 0 and 1, then multiply by N and store it in a long.
Untested
code:

#include <stdlib.h>

const long N = 987654321; /* upper limit */

int main(void) {
double d;
long result;
srand((unsigned ) time(NULL));
d = rand() / RAND_MAX;
result = d * N;
}


Thanks, I can see the logic there and it seems to do the trick!

Martin
Jul 22 '05 #5
Method Man wrote:
"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.

Thanks,
Martin

Assume N < LONG_MAX is your upper limit. I would generate a random (double)
number between 0 and 1, then multiply by N and store it in a long. Untested
code:

#include <stdlib.h>

const long N = 987654321; /* upper limit */

int main(void) {
double d;
long result;
srand((unsigned ) time(NULL));
d = rand() / RAND_MAX;
result = d * N;
}


You should be careful with code like this. While this will give you a
number between 1 and N, there are only RAND_MAX possible values it can
give you (in your case <40,000). Therefore the vast majority of numbers
will never occur. If this doesn't bother you thats fine. Just making
sure you are aware of it...
Jul 22 '05 #6
me
Method Man wrote:
"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.

Thanks,
Martin

Assume N < LONG_MAX is your upper limit. I would generate a random (double)
number between 0 and 1, then multiply by N and store it in a long. Untested
code:

#include <stdlib.h>

const long N = 987654321; /* upper limit */

int main(void) {
double d;
long result;
srand((unsigned ) time(NULL));
d = rand() / RAND_MAX;
result = d * N;
}

There's a problem with this code. Imagine, for example, you want a
random number between 0 and 256000, and you have an RNG that generates
numbers between 0 and 256. By your logic you could generate a random
number by doing (random() * 1000). But this would only generate a number
in the set {0,1000,2000,30 00,...,254000,2 55000,256000}, and so would not
be random....

cheers

pjw
Jul 22 '05 #7

"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...

"Method Man" <a@b.c> wrote in message
news:kD******** ************@re ad2.cgocable.ne t...

"Martin" <ma****@nospam. com> wrote in message
news:41******** *************** @news.syd.swift dsl.com.au...
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.

Thanks,
Martin


Assume N < LONG_MAX is your upper limit. I would generate a random
(double)
number between 0 and 1, then multiply by N and store it in a long.
Untested
code:

#include <stdlib.h>

const long N = 987654321; /* upper limit */

int main(void) {
double d;
long result;
srand((unsigned ) time(NULL));
d = rand() / RAND_MAX;
result = d * N;
}


Thanks, I can see the logic there and it seems to do the trick!


As others have mentioned, this code may work for your upper limit, but it
does not generate numbers in a uniform distribution (some numbers may never
get selected). See Ivan's post for alternate solutions.
Jul 22 '05 #8
On Sun, 14 Nov 2004 16:43:34 +0800 in comp.lang.c++, "Martin" <ma****@nospam. com> wrote,
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


Get a better random number generator.
See chapter 22.7 in Stroustrup.
See the Boost Random library.

Jul 22 '05 #9
Method Man wrote:
Assume N < LONG_MAX is your upper limit. I would generate a random
(double)
number between 0 and 1, then multiply by N and store it in a long.
Untested
code:

#include <stdlib.h>

const long N = 987654321; /* upper limit */

int main(void) {
double d;
long result;
srand((unsigned ) time(NULL));
d = rand() / RAND_MAX;
result = d * N;
}


Thanks, I can see the logic there and it seems to do the trick!


As others have mentioned, this code may work for your upper limit, but it
does not generate numbers in a uniform distribution (some numbers may never
get selected). See Ivan's post for alternate solutions.


<nitpicking>
The above generates only 1 number: 0
(or was it 2: 0 and N? I never can remember if rand()'s
return value includes or does not include RAND_MAX)
</nitpicking>

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #10

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

Similar topics

18
2649
by: Toby Newman | last post by:
I need to randomly choose one of four paths in my program. Using the tools I know, the best way I can think to do it is by doing something like the following: //============================== #include <stdlib.h> //allow rand() function int i; i = rand (); // i = any number of the set or if (0<=i<(4294967295/4))
36
6013
by: Michael B Allen | last post by:
Someone once posted the following macro on clc: #define randint(a,b) (a)+(((b)-(a)+1)*(float)rand()/RAND_MAX) Unfortunately it's flawed. If rand() returns RAND_MAX the result can be one larger than b. So can someone provide a *proper* macro (or function) that returns a random integer between (actually in) a range of values? For example randint(0, 999) could return:
11
5135
by: Olaf \El Blanco\ | last post by:
How can i generate random words? ('a'..'z') Is there any function that convert a number to it ascci char? My english is horrible! Here an example: function(65) return 'a'; Thank you!
8
2296
by: asdf | last post by:
I want a random number generator, the random number should be subject a uniform distribution in . Could you please give me some hints? Thanks.
22
3464
by: gagan.singh.arora | last post by:
Hi there. I want to generate random numbers with a given probability, say 80% even and 20% odd. Is it possible to implement such an algorithm in C?
13
4905
by: rhitx | last post by:
Hello: I'm trying create a random number generator, which will generate either number 1, 2, 3. I tried to do it like: int random_number() { int no_goal, rand_Number;
7
1881
by: alphaLaura | last post by:
Hi all - I'm just new to the group and I hope nobody minds me asking for some help. I currently have an assignment which deals with matrices (more specifically, Gauss-Seidel solving of matrices). One of the side tasks we have is to generate an NxN matrix of random numbers using the rand() function, but subject to the constraint that the absolute value of the diagonal element (a) must be greater than the sum of the absolute values of all...
13
2820
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 )
26
7927
by: bilgekhan | last post by:
What is the correct method for generating 2 independent random numbers? They will be compared whether they are equal. What about this method: srand(time(0)); int r1 = rand(); srand(rand()); int r2 = rand(); bool f = r1 == r2;
0
9696
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
10902
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9420
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...
1
7824
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7014
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
5680
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...
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3128
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.