473,756 Members | 7,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Random Number Not Seeding

I have two files:

sort_comparison .c++
my_sort.h

sort_comparison .c++ calls this code in my_sort.h:

void my_sort::fillAr ray(int arr[],int n)
{
// const int random_number_r ange=1000000;
const int random_number_r ange=100;
int number,xcell;
randomNumber rnd;
for (xcell=0;xcell< n;xcell++)
{
number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);
// arr[xcell]=rand();
}
}

The problem is that every array gets filled with the exact same data...
If I comment out:

number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);

and replace it with

arr[xcell]=rand();

I get random data in my arrays... The complete code for both files is
below. Can anyone tell me why

number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);

doesn't generate randomized data like "arr[xcell]=rand();"? Thanks.

////////////////////////////////////////////////////////////////////

//begin sort_comparison .c++
#include <ctime>
#include <iostream>
#include <string>
#include "../ftsoftds/include/d_random.h"
#include "../ftsoftds/include/d_sort.h" // Contains
selectionSort
//#include "../ftsoftds/include/d_timer.h"
#include "my_sort.h" // My sorting library.

using namespace std;

void printArray(stri ng name,int arr[],int n)
{
int cell;
cout<<name<<" Sort Array..."<<endl ;
for(cell=0;cell <n;cell++)
{
printf("%d ",arr[cell]);
}
cout<<endl;
}
////////////////////////////////////////////////////////////////////////////////
int main ()
{
// Declare five (5) integer arrays. Final array_size is 10,000 (ten
thousand).
const int array_size=25;
const int xrandom_number_ range=100;
int
array_selection _sort[array_size],array_insertio n_sort[array_size],
array_bubble_so rt[array_size],array_exchange _sort[array_size],
array_shell_sor t[array_size];
// Declare my_sort.h object (Did I reference this comment
correctly?).
my_sort my;
int cell,xnumber;
randomNumber xrnd;

/*
for(cell=0;cell <array_size;cel l++)
{
xnumber=xrnd.ra ndom(xrandom_nu mber_range);
array_selection _sort[cell]=xnumber;
}
for(cell=0;cell <array_size;cel l++)
{
printf("%d ",array_selecti on_sort[cell]);
}
cout<<endl;


for(cell=0;cell <array_size;cel l++)
{
xnumber=xrnd.ra ndom(xrandom_nu mber_range);
array_insertion _sort[cell]=xnumber;
}
for(cell=0;cell <array_size;cel l++)
{
printf("%d ",array_inserti on_sort[cell]);
}
cout<<endl;

for(cell=0;cell <array_size;cel l++)
{
array_exchange_ sort[cell]=4;
}
for(cell=0;cell <array_size;cel l++)
{
printf("%d ",array_exchang e_sort[cell]);
}
cout<<endl;
*/
my.fillArray(ar ray_selection_s ort,array_size) ;
my.fillArray(ar ray_insertion_s ort,array_size) ;
my.fillArray(ar ray_bubble_sort ,array_size);
my.fillArray(ar ray_exchange_so rt,array_size);
my.fillArray(ar ray_shell_sort, array_size);
// array_exchange_ sort[0]=99;

selectionSort(a rray_selection_ sort,array_size );
insertionSort(a rray_insertion_ sort,array_size );

// The following is used to verify that the arrays contain like data...
printArray("Sel ection",array_s election_sort,a rray_size);
printArray("Ins ertion",array_i nsertion_sort,a rray_size);
printArray("Bub ble",array_bubb le_sort,array_s ize);
printArray("Exc hange",array_ex change_sort,arr ay_size);
printArray("She ll",array_shell _sort,array_siz e);

return 0;
}
//end sort_comparison .c++

///////////////////////////////////////////////////////////////////////

//begin my_sort.h
class my_sort
{
int x, y;
public:
void bubbleSort(int arr[],int n);
void fillArray(int arr[],int n);
};

void my_sort::bubble Sort(int arr[],int n)
{
int i,j;
for(i = 0; i < n; i++)
for(j = i+1; j < n; j++)
if (arr[i] > arr[j]) { // swap arr[i] and arr[j]
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
////////////////////////////////////////////////////////////////////////////////
void my_sort::fillAr ray(int arr[],int n)
{
// const int random_number_r ange=1000000;
const int random_number_r ange=100;
int number,xcell;
randomNumber rnd;
for (xcell=0;xcell< n;xcell++)
{
number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);
// arr[xcell]=rand();
}
}
//end my_sort.h

Aug 17 '05 #1
4 2697
Jack wrote:
I have two files:

sort_comparison .c++
my_sort.h

sort_comparison .c++ calls this code in my_sort.h:

void my_sort::fillAr ray(int arr[],int n)
{
// const int random_number_r ange=1000000;
const int random_number_r ange=100;
int number,xcell;
randomNumber rnd;
for (xcell=0;xcell< n;xcell++)
{
number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);
// arr[xcell]=rand();
}
}

The problem is that every array gets filled with the exact same data...
If I comment out:

number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);

and replace it with

arr[xcell]=rand();

I get random data in my arrays... The complete code for both files is
below. Can anyone tell me why

number=rnd.rand om(random_numbe r_range);
arr[xcell]=rnd.random(num ber);

doesn't generate randomized data like "arr[xcell]=rand();"? Thanks.

[...]


'rand' is a standard function. Its seed is controlled by another standard
function, 'srand'. Any program that doesn't call 'srand' behaves as if
it was called with the argument 0.

Now, we can tell you some things about 'srand' and 'rand', but apparently,
they work fine for you. You OTOH have a problem with 'rnd', which is
an object of type 'randomNumber'. This is not a standard class. So you
would have to tell us what it is before we can explain what the difference
is between it and the standard library functions.

One speculation I'll allow myself: it is possible that you are supposed to
have only one 'randomNumber' object in your program. It _probably_ seeds
itself with something upon creation, and then the sequence sustains itself
somehow. If you keep recreating that object every time you call your
function, it's possible that it just restarts the sequence...

V
Aug 17 '05 #2
Ahhh, your reference to 'srand' makes sense. Below is the code to
'd_random.h' which contains the 'randomNumber' class. Can you take a
look at it and make any recommendations on possibly adding 'srand'? I'm
not a hardcore C++ coder... Thanks.

$ cat d_random.h
#include <iostream>
#include <time.h>

using namespace std;

// generate random numbers
class randomNumber
{
public:
// initialize the random number generator
randomNumber(lo ng s = 0);

// return a 32-bit random integer m, 1 <= m <= 2^31-2
long random();

// return a 32-bit random integer m, 0 <= m <= n-1,
// where n <= 2^31-1
long random(long n);

// return a real number x, 0 <= x < 1
double frandom();

private:
static const long A;
static const long M;
static const long Q;
static const long R;

long seed;
};

const long randomNumber::A = 48271;
const long randomNumber::M = 2147483647;
const long randomNumber::Q = M / A;
const long randomNumber::R = M % A;

randomNumber::r andomNumber(lon g s)
{
if (s < 0)
s = 0;

if (s == 0)
{
// get time of day in seconds since 12:00 AM,
// January 1, 1970
long t_time = time(NULL);

// mix-up bits by squaring
t_time *= t_time;
// result can overflow. handle cases
// > 0, < 0, = 0
if (t_time > 0)
s = t_time ^ 0x5EECE66DL;
else if (t_time < 0)
s = (t_time & 0x7fffffff) ^ 0x5EECE66DL;
else
s = 0x5EECE66DL;
}

seed = s;
}

long randomNumber::r andom()
{
long tmpSeed = A * ( seed % Q ) - R * ( seed / Q );

if( tmpSeed >= 0 )
seed = tmpSeed;
else
seed = tmpSeed + M;

return seed;
}

long randomNumber::r andom(long n)
{
double fraction = double(random() )/double(M);

return int(fraction * n);
}

double randomNumber::f random()
{
return double(random() )/double(M);
}

Aug 17 '05 #3
Jack wrote:
Ahhh, your reference to 'srand' makes sense. Below is the code to
'd_random.h' which contains the 'randomNumber' class. Can you take a
look at it and make any recommendations on possibly adding 'srand'?
AFAICS, there is no need for it. The constructor argument plays the
seed role. Construction of an object with the default argument value
(zero, 0) seeds the generator with the time, any other positive value
is kept as the seed.

I still think you should have a global object of type 'randomNumber'
in your program to keep the sequence instead of restarting it every
time when your function 'fillArray' is called. It is quite possible
that while creating new 'randomNumber' object _might_ generate the
sequence of pseudo-random numbers different every time, if all calls
happen to be within the same second (which is not unreasonable in our
times, when computers are fast), then the sequence generated would
be exactly the same for every call to 'fillArray'.

I recommend just modifying your definition of 'rnd' object in your
'fillArray' function to 'static':

void my_sort::fillAr ray(int arr[],int n)
{
// const int random_number_r ange=1000000;
const int random_number_r ange=100;
int number,xcell;
static randomNumber rnd;
...
Victor

I'm
not a hardcore C++ coder... Thanks.
Neither am I, really... No, honestly, I am not... I swear!
[..]

Aug 17 '05 #4
Dude! Sweet! The "static" did the trick... Now I have to read what
that's doing :) .

What you said about all calls happening in the same second made sense
too. So I put a few second loop between two fills, and what do you
know... Random data...

Most cool!

Aug 18 '05 #5

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

Similar topics

10
2909
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
7380
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
104
5173
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.
13
3197
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...
6
5910
by: Intiha | last post by:
Hello all, I am trying to generate random seeds for my simulations. currently i was using srand(time(NULL); for this purpose. But for confidence in my results i ran it using a script in a loop. Since the time b/w execution is very similar, many simulation runs resulted in exact same results. Is there a better way of seeding the random number generator in c/c++
11
3603
by: Kevin Williamson | last post by:
Hi, I've written a lottery programme in PHP that selects 10 winners a week from approximately 18,000 shares. The problem I have is that of the ten winners one week the same share number was drawn the next week and an adjacent share number the following week (that just happened to be owned by the same member) The program is now being looked at suspisciously.
2
3660
by: HumanJHawkins | last post by:
I wrote this question a little differently in the MFC group since it is a bit of a different environment than pure C++, but I hope you will forgive the similarities if anyone is reading both groups. Basically, I need to seed the random number generator in 4 seperate threads at once. So, I can't use the current time as the random seed, because then all four threads end up with the same series of (therefore non-random) numbers. Is there...
8
3914
by: Daniel | last post by:
Hey guys Using Random(), how random is it, is it possible to be predicted? I have a requirement for a very good random number generator. I was doing something such as: Random randomSeed = new Random((int)_seedTimer.ElapsedTicks); _random = new Random(randomSeed.Next(0,99999999)); return random.Next(min, max);
11
3022
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.
0
9117
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
9894
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
9679
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
9541
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...
1
7078
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
4955
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...
0
5156
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3651
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
3
2508
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.