473,836 Members | 1,429 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Random number generator.

I am looking for a random number generator implementation with the
following requirements:

- Thread-safe, re-entrant.
- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.
- Relatively uniform, does not have to be perfect.

The application is not a security or statistics application, the
quality of numbers is not a priority although a fairly uniform
distribution would be nice. The application I am using it for is
generating random numbers for controlling audio and video effects, and
the user must be able to specify a seed to produce the same sequence
of "random" numbers every time. However, there may be many such
"streams" of random numbers being generated at the same time, each
which is seeded with it's own starting value and must produce
sequences independent of every other "stream".

This is a minor feature I want to add to my application (which is just
using rand() with no predictability right now). Therefore, to be
honest, I am not interested in doing any major amount of work or
research. I am wondering if anybody knows of a decent implementation
that is easy to drop in to existing code (there doesn't appear to be
anything in the STL, is there?).

Thanks,
Jason
Jun 27 '08 #1
14 4777
On 2008-05-31 19:37, ja************@ gmail.com wrote:
On May 31, 1:30 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
>I do not know about the uniformity, but using srand() and calling it
with the last generated number (of a function thereof) should make it
re-entrant.

Thanks, I guess that is a pretty obvious solution. So something like
this:

class RandomNumber {
public:
RandomNumber (int seed) : seed_(seed) { }
void Seed (int seed) { seed_ = seed; }
int Next () { srand(seed_); return rand(); }
private:
int seed_;
};

My question there is, is rand() guaranteed to give the same sequence
of numbers given a seed on every platform and every machine, for every
standard library implementation? My particular application does run on
many platforms and many computers, and the user will expect to see the
exact same results on every machine given the same inputs.
No, if you need consistency on many different platforms you need to get
some other function. The wikipedia article about linear congruential
generators gives an algorithm you can use. Or you can google for pseudo
random number generators, there should be a few libraries available.

--
Erik Wikström
Jun 27 '08 #2
On May 31, 2:09 pm, "jason.cipri... @gmail.com"
<jason.cipri... @gmail.comwrote :
This is a minor feature I want to add to my application (which is just
using rand() with no predictability right now). Therefore, to be
honest, I am not interested in doing any major amount of work or
research. I am wondering if anybody knows of a decent implementation
that is easy to drop in to existing code (there doesn't appear to be
anything in the STL, is there?).

Thanks,
Jason
From man 3 rand

POSIX.1-2001 gives the following example of an implementation of
rand() and srand(), possibly useful when one needs the same sequence
on two different machines.
static unsigned long next = 1;

/* RAND_MAX assumed to be 32767 */
int myrand(void) {
next = next * 1103515245 + 12345;
return((unsigne d)(next/65536) % 32768);
}

void mysrand(unsigne d seed) {
next = seed;
}
Jun 27 '08 #3
ja************@ gmail.com wrote:
I am looking for a random number generator implementation with the
following requirements:

- Thread-safe, re-entrant.
- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.
- Relatively uniform, does not have to be perfect.

The application is not a security or statistics application, the
quality of numbers is not a priority although a fairly uniform
distribution would be nice. The application I am using it for is
generating random numbers for controlling audio and video effects, and
the user must be able to specify a seed to produce the same sequence
of "random" numbers every time. However, there may be many such
"streams" of random numbers being generated at the same time, each
which is seeded with it's own starting value and must produce
sequences independent of every other "stream".

This is a minor feature I want to add to my application (which is just
using rand() with no predictability right now). Therefore, to be
honest, I am not interested in doing any major amount of work or
research. I am wondering if anybody knows of a decent implementation
that is easy to drop in to existing code (there doesn't appear to be
anything in the STL, is there?).
Assuming that your compiler supports 64 bit long long types, you could use
this simple linear congruence RNG, which has reasonable properties:
// Line26.cc
// =========
/*
Implementing a variation of the RNG from
Table 1 [TAOCP, 3.3.4], line 26.
*/

#ifndef KUBUX_LINE26
#define KUBUX_LINE26

namespace kubux {

class Line26 {

unsigned long long state;

static const unsigned long long a =
636413622384679 3005ull; // cong 5 mod 8

static const unsigned long long c =
314159ull; // odd

public:

Line26 ( unsigned long seed = 0 )
: state ( 126871263818671 ull + a * seed )
{}

unsigned long min ( void ) const {
return ( 0 );
}

unsigned long max ( void ) const {
return ( 0xfffffffful );
}

unsigned long operator() ( void ) {
state = state * a + c & 0xfffffffffffff fffull;
return ( state >32 );
}

unsigned long operator() ( unsigned long n ) {
unsigned long long bucket_size =
}

};

} // kubux

#endif

// end of file

#include <iostream>
#include <iomanip>

int main ( void ) {
kubux::Line26 rng;
while ( true ) {
std::cout << std::hex << rng() << '\n';
}
}
Best

Kai-Uwe Bux

Jun 27 '08 #4
ja************@ gmail.com wrote:
On May 31, 1:37 pm, "jason.cipri... @gmail.com"
<jason.cipri... @gmail.comwrote :
>class RandomNumber {
public:
RandomNumber (int seed) : seed_(seed) { }
void Seed (int seed) { seed_ = seed; }
int Next () { srand(seed_); return rand(); }
private:
int seed_;
};

Oops. That should, of course, be:

int Next () {
srand(seed_);
seed_ = rand(); // <----
return seed_;
}
Bad idea: that will limit the period to at most RAND_MAX+1. Moreover, you
loose all the theory behind the implementation of rand(), which probably
exists even although it might not be documented. In particular, you could
end up with something that is not even uniform.
Best

Kai-Uwe Bux
Jun 27 '08 #5
Kai-Uwe Bux wrote:
ja************@ gmail.com wrote:
>I am looking for a random number generator implementation with the
following requirements:

- Thread-safe, re-entrant.
- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.
- Relatively uniform, does not have to be perfect.

The application is not a security or statistics application, the
quality of numbers is not a priority although a fairly uniform
distribution would be nice. The application I am using it for is
generating random numbers for controlling audio and video effects, and
the user must be able to specify a seed to produce the same sequence
of "random" numbers every time. However, there may be many such
"streams" of random numbers being generated at the same time, each
which is seeded with it's own starting value and must produce
sequences independent of every other "stream".

This is a minor feature I want to add to my application (which is just
using rand() with no predictability right now). Therefore, to be
honest, I am not interested in doing any major amount of work or
research. I am wondering if anybody knows of a decent implementation
that is easy to drop in to existing code (there doesn't appear to be
anything in the STL, is there?).

Assuming that your compiler supports 64 bit long long types, you could use
this simple linear congruence RNG, which has reasonable properties:
[oops: missed the body of operator()( bound )]

// Line26.cc (C) Kai-Uwe Bux [2008]
// =============== =============== ==
/*
Implementing a variation of the RNG from
Table 1 [TAOCP, 3.3.4], line 26.
*/

#ifndef KUBUX_LINE26
#define KUBUX_LINE26

namespace kubux {

class Line26 {

unsigned long long state;

static const unsigned long long a =
636413622384679 3005ull; // cong 5 mod 8

static const unsigned long long c =
314159ull; // odd

public:

Line26 ( unsigned long seed = 0 )
: state ( 126871263818671 ull + a * seed )
{}

unsigned long min ( void ) const {
return ( 0 );
}

unsigned long max ( void ) const {
return ( 0xfffffffful );
}

unsigned long operator() ( void ) {
state = state * a + c & 0xfffffffffffff fffull;
return ( state >32 );
}

unsigned long operator() ( unsigned long n ) {
unsigned long long bucket_size = (unsigned long long)(-1) / n;
unsigned long long past_valid = bucket_size * n;
do {
state = state * a + c & 0xfffffffffffff fffull;
} while ( state >= past_valid );
return ( state / bucket_size );
}

};

} // kubux

#endif

// end of file

#include <iostream>
#include <iomanip>

int main ( void ) {
kubux::Line26 rng;
while ( true ) {
std::cout << rng(10u) << '\n';
}
}
Best

Kai-Uwe Bux
Jun 27 '08 #6
In article <f7fdf24f-cf85-42a2-aa7d-3cd2eb9c891b@
34g2000hsf.goog legroups.com>, ja************@ gmail.com says...
I am looking for a random number generator implementation with the
following requirements:

- Thread-safe, re-entrant.
- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.
- Relatively uniform, does not have to be perfect.
TR1 has a <randomheader containing some templates for random number
generation. C++ 0x also contains some random number generation
templates. While most of TR1 was adopted into C++ 0x with little or no
change, IIRC, the part dealing with random number generation was
extensively modified.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #7
On May 31, 7:09*pm, "jason.cipri... @gmail.com"
<jason.cipri... @gmail.comwrote :
I am looking for a random number generator implementation with the
following requirements:

*- Thread-safe, re-entrant.
*- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.
*- Relatively uniform, does not have to be perfect.

The application is not a security or statistics application, the
quality of numbers is not a priority although a fairly uniform
distribution would be nice. The application I am using it for is
generating random numbers for controlling audio and video effects, and
the user must be able to specify a seed to produce the same sequence
of "random" numbers every time. However, there may be many such
"streams" of random numbers being generated at the same time, each
which is seeded with it's own starting value and must produce
sequences independent of every other "stream".

This is a minor feature I want to add to my application (which is just
using rand() with no predictability right now). Therefore, to be
honest, I am not interested in doing any major amount of work or
research. I am wondering if anybody knows of a decent implementation
that is easy to drop in to existing code (there doesn't appear to be
anything in the STL, is there?).

Thanks,
Jason
Why don't you just use the boost generator one ?
You can find more info here:

http://www.boost.org/doc/libs/1_35_0...enerators.html
Jun 27 '08 #8
Sam
ja************@ gmail.com writes:
I am looking for a random number generator implementation with the
following requirements:

- Thread-safe, re-entrant.
- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.
These two requirements are mutually exclusive, unless you have very, very
precise control over multiple threads' invocation of your random number
generation function.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkh BqKUACgkQx9p3GY HlUOI7OgCdEU8Gs 4v2Q+Iprd27F/VunZL/
dZ0An3CNfoCeLhA +cELzDRowwAmcB2 xh
=e+k7
-----END PGP SIGNATURE-----

Jun 27 '08 #9
On 2008-05-31 15:36:05 -0400, Sam <sa*@email-scan.comsaid:
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.

--=_mimegpg-commodore.email-scan.com-5848-1212262565-0002
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit

ja************@ gmail.com writes:
>I am looking for a random number generator implementation with the
following requirements:

- Thread-safe, re-entrant.
- Produces consistently reproducible sequences of psuedo-random
numbers given a seed.

These two requirements are mutually exclusive, unless you have very, very
precise control over multiple threads' invocation of your random number
generation function.
Well, yes and no. Read literally, yes. In fact, no problem: write a
generator type that holds its state in an object, and use one object
per thread. That's one of the key ideas in the TR1/C++0x random number
generators.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jun 27 '08 #10

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

Similar topics

1
3706
by: Brandon Michael Moore | last post by:
I'm trying to test a web application using a tool written in python. I would like to be able to generate random values to put in fields. I would like to be able to generate random dates (in a specified range), random strings (specifying allowed characters and a distribution of lengths), or choose randomly between several generators (for better control of the distribution of values). Is there any library for this sort of thing in Python?...
10
2914
by: Sonoman | last post by:
Hi all: I am trying to write a simple program that simulates asking several persons their birth day and it counts how many persons are asked until two have the same birth day. The problem that I have is that the first loop I get a sequence of random numbers untuil I get a match, BUT then on the following loops I get the SAME random(?) sequence. I am using rand(). I do not want to get too fancy with the random number generator, but is there...
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
70
6299
by: Ben Pfaff | last post by:
One issue that comes up fairly often around here is the poor quality of the pseudo-random number generators supplied with many C implementations. As a result, we have to recommend things like using the high-order bits returned by rand() instead of the low-order bits, avoiding using rand() for anything that wants decently random numbers, not using rand() if you want more than approx. UINT_MAX total different sequences, and so on. So I...
5
3355
by: Peteroid | last post by:
I know how to use rand() to generate random POSITIVE-INTEGER numbers. But, I'd like to generate a random DOUBLE number in the range of 0.0 to 1.0 with resolution of a double (i.e., every possible double value in the range could come up with equal probability). I'd also like to be able to seed this generator (e.g., via the clock) so that the same sequence of random values don't come up every time. Anybody have an easy and fast...
104
5208
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
5234
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?
13
3203
by: porterboy76 | last post by:
If you only use a 32 bit seed for a random number generator, does that mean you can only ever produce a maximum of 2^32 (approx 4 billion) different sequences? What about the Mersenne Twister, with it's massive period of 2^19937-1. Will you only ever have access to a tiny portion of this ring of numbers, if you only use a 32-bit seed? Will this set of sequences be confined to the beginning of the period, ie, your sequence will have to...
11
3026
TTCEric
by: TTCEric | last post by:
This will be original. I promise. I cannot get the random number generator to work. I tried seeding with Date.Now.Milliseconds, it still results in the same values. What I have are arrays of values. I get a random index value for each array so I can pull the data from them.
16
2089
by: raylopez99 | last post by:
For the public record. RL public void IterateOne() { Random myRandom = new Random(); //declare Random outside the iteration for (int j = 0; j < Max; j++) {
0
9825
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10854
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...
1
10601
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,...
0
10260
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
9388
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 projectplanning, coding, testing, and deploymentwithout 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
5652
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
4460
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
4023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
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.