473,897 Members | 3,321 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Random numbers

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 )
{
// return a uniformly distributed random number R in the range: 0 <=
R <= (num-1)
}

I also would like this to be as executionally fast as possible. I have been
trying to to this using rand() as my basis, but everything I try ends up
with one problem or another (e.g., outside of range, not evenly distributed,
execution too long).

I'm using VS C++ 2005 Express Edition (managed /clr pure), and was hoping
that there is a better alternative to rand( ) as the basis of random
numbers, since this always generates an evenly distributed number from 0 to
RAND_MAX (0x7fff), which is not easily adapted to the task I've described
above...

If there is a cheap third-party class I could buy to do this, I'd be
interested in that too...

Thanx in advance for responses! :)
Jun 27 '07 #1
13 2823
OK, I'm an idiot (feel free to throw stones....hehe) .

Here I am looking for some class in .NET that produces random numbers, and
it never occurs to me to look for a class named 'Random'. Which, of course,
exists; and, of course, does exactly what I want! :)
"Peter Oliphant" <po*******@Roun dTripInc.comwro te in message
news:uW******** ******@TK2MSFTN GP02.phx.gbl...
>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 )
{
// return a uniformly distributed random number R in the range: 0 <=
R <= (num-1)
}

I also would like this to be as executionally fast as possible. I have
been trying to to this using rand() as my basis, but everything I try ends
up with one problem or another (e.g., outside of range, not evenly
distributed, execution too long).

I'm using VS C++ 2005 Express Edition (managed /clr pure), and was hoping
that there is a better alternative to rand( ) as the basis of random
numbers, since this always generates an evenly distributed number from 0
to RAND_MAX (0x7fff), which is not easily adapted to the task I've
described above...

If there is a cheap third-party class I could buy to do this, I'd be
interested in that too...

Thanx in advance for responses! :)

Jun 27 '07 #2
"Peter Oliphant" <po*******@Roun dTripInc.comwro te in message
news:uW******** ******@TK2MSFTN GP02.phx.gbl...
>I would like to be able to create a random number generator that produces
evenly distributed random numbers up to given number.
A quick, though, not perfect, method is to compute a random number with
rand() and then take the remainder of a division.

e.g.

rand() % 10

yields numbers in {0 ... 9}. if you want {1 ... 10} add 1.

Of course, since the highest number rand() returns is RAND_MAX and that is
not evenly divisible by 10, your numbers won't have an even distribution.

Naively, I'd suggest in that case that you pick your own maximum such that
it is evenly divisble by the size of the range in question and discard
anything above it.

If you need numbers larger than RAND_MAX you can put two 16 bit numbers
together to make a 32 bit number. See the MAKELONG macro for example.

Of course, this is the kind of problem that has no doubt been faced and
solved thousands of times, so if you need a "good" random number generator I
suggest that you search for an algorithm or make friends with a PhD in math.
;-)

Regards,
Will
www.ivrforbeginners.com
Jun 27 '07 #3
Hi William,

Thanx!

Yeah, I know of the method you speak. There are, in fact two basic methods I
tried, but each fails my 'criteria' for one reason or another.

For the purposes of the dicussion below, the range of numbers to find a
random number in is 0 to (max-1).

The method you mentioned, ala getting a big random number and then
modulo'ing it with the 'max' value, does always return a random number in
range and does span the whole range, but unless the 'max' is a integral
divisor of RAND_MAX (which means it has to be a power of 2) the results will
not be evenly distributed (ala, the lower numbers will be produced more than
the upper numbers).

The other basic method is to keep getting big random numbers until one falls
in range, rejecting any out of range. As long as the big random numbers can
range from 0 to outside 'max' (and are evely distributed themselves), this
does indeed pick an evenly distributed random number in range, and does span
the range. But it is execution-time VERY non-deterministic, and in fact can
take a very long time (computer exectution-wise) to deal with some 'max'
values. For example, trying to get a result of 0 or 1 (i.e., max = 2) and
using big random numbers up to 64K will find one in range on average in only
1 in 32K tries, and thus on average would take many failed iterations to
eventually get one in range.

Thus I tried separating cases based on 'max', such as masking a big random
number with 0xF for 'max's less than 16. This works, but one ends up with
many many many case, and it gets so complex, the mechanism to figure out
which method to use becomes intrusive.

Thus, the solution I found was a cheat....sort of....hehe...it turns out
there exists a Random class that has a Next(max) method that produces a
non-negative random number less than 'max', where 'max' can be 32-bits in
size (i.e., exactly what I'm looking for!!!)...

I've impleneted it, but have yet to see if the MS class is indeed uniformly
distributed. I will do tests to be sure, but I was VERY glad to find this
class!

[==P==]

"William DePalo [MVP VC++]" <wi***********@ mvps.orgwrote in message
news:uj******** ******@TK2MSFTN GP02.phx.gbl...
"Peter Oliphant" <po*******@Roun dTripInc.comwro te in message
news:uW******** ******@TK2MSFTN GP02.phx.gbl...
>>I would like to be able to create a random number generator that produces
evenly distributed random numbers up to given number.

A quick, though, not perfect, method is to compute a random number with
rand() and then take the remainder of a division.

e.g.

rand() % 10

yields numbers in {0 ... 9}. if you want {1 ... 10} add 1.

Of course, since the highest number rand() returns is RAND_MAX and that is
not evenly divisible by 10, your numbers won't have an even distribution.

Naively, I'd suggest in that case that you pick your own maximum such that
it is evenly divisble by the size of the range in question and discard
anything above it.

If you need numbers larger than RAND_MAX you can put two 16 bit numbers
together to make a 32 bit number. See the MAKELONG macro for example.

Of course, this is the kind of problem that has no doubt been faced and
solved thousands of times, so if you need a "good" random number generator
I suggest that you search for an algorithm or make friends with a PhD in
math. ;-)

Regards,
Will
www.ivrforbeginners.com


Jun 27 '07 #4
In article <uW************ **@TK2MSFTNGP02 .phx.gbl>,
Peter Oliphant <po*******@Roun dTripInc.comwro te:
>I would like to be able to create a random number generator that
produces evenly distributed random numbers up to given number.
Computer-generated random numbers tend to not be very good, unless
you REALLY know what you're doing. rand() in the C standard library
tends to be barely usable-- on a lot of systems, it only has 16-bit
accuracy. You really should stick with finding a better random number
generator and use it -- the Mersenne Twister from
http://www.math.sci.hiroshima-u.ac.j...at/MT/emt.html has gotten a
bunch of good reviews, and is quite free (BSD license, which basically
says "feel free to use it, even in commercial apps." That site has C
code available, and allows you to get a random # up to a range.

Nathan Mates
--
<*Nathan Mates - personal webpage http://www.visi.com/~nathan/
# Programmer at Pandemic Studios -- http://www.pandemicstudios.com/
# NOT speaking for Pandemic Studios. "Care not what the neighbors
# think. What are the facts, and to how many decimal places?" -R.A. Heinlein
Jun 27 '07 #5
Hi,
Yeah, I know of the method you speak. There are, in fact two basic
methods I tried, but each fails my 'criteria' for one reason or
another.
For the purposes of the dicussion below, the range of numbers to find
a random number in is 0 to (max-1).

The method you mentioned, ala getting a big random number and then
modulo'ing it with the 'max' value, does always return a random
number in range and does span the whole range, but unless the 'max'
is a integral divisor of RAND_MAX (which means it has to be a power
of 2) the results will not be evenly distributed (ala, the lower
numbers will be produced more than the upper numbers).

The other basic method is to keep getting big random numbers until
one falls in range, rejecting any out of range. As long as the big
random numbers can range from 0 to outside 'max' (and are evely
distributed themselves), this does indeed pick an evenly distributed
random number in range, and does span the range. But it is
execution-time VERY non-deterministic
Another one would be

long nDiv = RAND_MAX / yourMax;

long n = (rand() / nDiv) % yourMax;

So if RAND_MAX == 100 and you want 0..9 then you get 0..9 as 0 and 10..19 as
1 and so on.

You might get yourMax as result so I added the modulo operation to address
that.
it turns
out there exists a Random class that has a Next(max) method that
produces a non-negative random number less than 'max', where 'max'
can be 32-bits in size (i.e., exactly what I'm looking for!!!)...

I've impleneted it, but have yet to see if the MS class is indeed
uniformly distributed. I will do tests to be sure, but I was VERY
glad to find this class!
Im curious of your findings.

--
SvenC

Jun 27 '07 #6
On Wed, 27 Jun 2007 09:10:27 -0700, "Peter Oliphant"
<po*******@Roun dTripInc.comwro te:
>The other basic method is to keep getting big random numbers until one falls
in range, rejecting any out of range. As long as the big random numbers can
range from 0 to outside 'max' (and are evely distributed themselves), this
does indeed pick an evenly distributed random number in range, and does span
the range. But it is execution-time VERY non-deterministic, and in fact can
take a very long time (computer exectution-wise) to deal with some 'max'
values. For example, trying to get a result of 0 or 1 (i.e., max = 2) and
using big random numbers up to 64K will find one in range on average in only
1 in 32K tries, and thus on average would take many failed iterations to
eventually get one in range.
You don't need to do that much iteration, or for max = 2 with odd RAND_MAX,
any at all. See:

http://c-faq.com/lib/randrange.html

--
Doug Harrison
Visual C++ MVP
Jun 27 '07 #7
On Wed, 27 Jun 2007 18:27:18 +0200, "SvenC" <Sv***@communit y.nospamwrote:
>Another one would be

long nDiv = RAND_MAX / yourMax;

long n = (rand() / nDiv) % yourMax;

So if RAND_MAX == 100 and you want 0..9 then you get 0..9 as 0 and 10..19 as
1 and so on.

You might get yourMax as result so I added the modulo operation to address
that.
That produces an uneven distribution a lot of the time. See the link to the
C FAQ I posted in my reply to Peter for an approach that doesn't. (To see
the problem in your approach, consider RAND_MAX = 100 and yourMax = 99.
Then nDiv is 1, rand()/nDiv is 0..99, and 99%99 is 0. So you will have 0
appearing twice as often as any other number.)

--
Doug Harrison
Visual C++ MVP
Jun 27 '07 #8
Doug Harrison [MVP] wrote:
On Wed, 27 Jun 2007 18:27:18 +0200, "SvenC" <Sv***@communit y.nospam>
wrote:
>Another one would be

long nDiv = RAND_MAX / yourMax;

long n = (rand() / nDiv) % yourMax;

So if RAND_MAX == 100 and you want 0..9 then you get 0..9 as 0 and
10..19 as 1 and so on.

You might get yourMax as result so I added the modulo operation to
address that.

That produces an uneven distribution a lot of the time. See the link
to the C FAQ I posted in my reply to Peter for an approach that
doesn't. (To see the problem in your approach, consider RAND_MAX =
100 and yourMax = 99. Then nDiv is 1, rand()/nDiv is 0..99, and 99%99
is 0. So you will have 0 appearing twice as often as any other
number.)
Yes, figured that out after thinking again about my post.

I'll have a look at the FAQ.

--
SvenC
Jun 27 '07 #9
Keep in mind, my desire is to produce random rumber is a ranges GREATER than
RAND_MAX, and that the range be sometihng I can establish on the fly (i.e.,
it's a variable).

I did experiements on the innate Random class, and it works just fine. It
can be seeded (I use current 'time'), and can range from 0 to ANY number up
to 31 bits (the return value is signed). 31-bits gets me ranges up to 2
billion or so, which is (more than) just fine for my purposes! : )

All that is required is the following:

Random^ R = gcnew Random( /* int seed if desired*/ ) ;

int r = R->Next( max ) ; // 0 <= r < max

[==P==]

"Doug Harrison [MVP]" <ds*@mvps.orgwr ote in message
news:1f******** *************** *********@4ax.c om...
On Wed, 27 Jun 2007 09:10:27 -0700, "Peter Oliphant"
<po*******@Roun dTripInc.comwro te:
>>The other basic method is to keep getting big random numbers until one
falls
in range, rejecting any out of range. As long as the big random numbers
can
range from 0 to outside 'max' (and are evely distributed themselves), this
does indeed pick an evenly distributed random number in range, and does
span
the range. But it is execution-time VERY non-deterministic, and in fact
can
take a very long time (computer exectution-wise) to deal with some 'max'
values. For example, trying to get a result of 0 or 1 (i.e., max = 2) and
using big random numbers up to 64K will find one in range on average in
only
1 in 32K tries, and thus on average would take many failed iterations to
eventually get one in range.

You don't need to do that much iteration, or for max = 2 with odd
RAND_MAX,
any at all. See:

http://c-faq.com/lib/randrange.html

--
Doug Harrison
Visual C++ MVP

Jun 27 '07 #10

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

Similar topics

10
11968
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
3
7383
by: Joe | last post by:
Hi, I have been working on some code that requires a high use of random numbers within. Mostly I either have to either: 1) flip a coin i.e. 0 or 1, or 2) generate a double between 0 and 1. I have utilised the following random number source code http://www.agner.org/random/ What I have found is that there is a problem with seeding. The code generates a seed based on time(0). I have found that I need to increment
21
3046
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
2406
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
5232
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
5238
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?
21
13525
by: chico_yallin | last post by:
I just wana make a random id number based on4 digits-for examples?? Thanks in Advance Ch.Yallin
6
11759
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
7253
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
9990
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
9837
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
10850
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...
1
10941
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
8032
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
6074
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4698
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
4293
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3300
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.