473,387 Members | 1,516 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Random number generator for use with random_shuffle

I had a need to create my own RandomNumberGenerator class, for use with
random_shuffle (I did not want the same sequence generated each time).
I looked up an example provided by Nicolai M. Josuttis, in his
fantastic book : The C++ Standard Library - A Tutorial and Reference
(http://www.josuttis.com/libbook/). Here is what he had:

class MyRandom {
public:
ptrdiff_t operator() (ptrdiff_t max) {
double tmp;
tmp = static_cast<double>(rand())
/ static_cast<double>(RAND_MAX);
return static_cast<ptrdiff_t>(tmp * max);
}
};

I adapted it as follows:
struct RandomNumberGenerator
{
ptrdiff_t operator() (ptrdiff_t diffVal)
{
struct timeval tod;
gettimeofday(&tod, 0);
srand(tod.tv_sec + tod.tv_usec);
int randVal = rand();

double retVal;
retVal = static_cast<double>(randVal) /
static_cast<double>(RAND_MAX);
return static_cast<ptrdiff_t>(retVal * diffVal);
}
};
Now here's the funny part. If I don't divide retVal by
static_cast<double>(RAND_MAX), I am getting a core dump.
Any ideas what could be causing this?

A simple program that operates on a text file and randomly shuffles its
lines follows. I am able to reproduce the coredump with this simple
program

Thx,
Song
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <sys/time.h>

using namespace std;

/////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////
struct RandomNumberGenerator
{
#define CAUSE_COREDUMP

#ifdef CAUSE_COREDUMP
ptrdiff_t operator() (ptrdiff_t diffVal)
{
struct timeval tod;
gettimeofday(&tod, 0);
srand(tod.tv_sec + tod.tv_usec);
int randVal = rand();

double retVal;
retVal = static_cast<double>(randVal);
return static_cast<ptrdiff_t>(retVal * diffVal);
}
#else // no core-dump
ptrdiff_t operator() (ptrdiff_t diffVal)
{
struct timeval tod;
gettimeofday(&tod, 0);
srand(tod.tv_sec + tod.tv_usec);
int randVal = rand();

double retVal;
retVal = static_cast<double>(randVal) /
static_cast<double>(RAND_MAX);
return static_cast<ptrdiff_t>(retVal * diffVal);
}
#endif // CAUSE_COREDUMP
};

/////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////
int
main(int argc, char* argv[])
{
if(argc == 1)
{
cerr << "usage: " << argv[0] << " <input-file>" << endl;
return 1;
}
ifstream ifs(argv[1]);
if(!ifs)
{
cerr << "Cannot open file " << argv[1] << " ....exiting" << endl;
return 2;
}

string line;

vector<stringlineColl;

while(getline(ifs, line))
{
if(line.empty()) continue;

lineColl.push_back(line);
}

if(!lineColl.empty())
{
RandomNumberGenerator rng;
random_shuffle(lineColl.begin(), lineColl.end(), rng);

// print each entry in the collection on a separate line
copy (lineColl.begin(), lineColl.end(), ostream_iterator<string>
(cout, "\n"));
}

return 0;
}

Dec 17 '06 #1
1 2769
On Dec 17, 7:44 pm, "Generic Usenet Account" <use...@sta.samsung.com>
wrote:
I had a need to create my own RandomNumberGenerator class, for use with
random_shuffle (I did not want the same sequence generated each time).
I looked up an example provided by Nicolai M. Josuttis, in his
fantastic book : The C++ Standard Library - A Tutorial and Reference
(http://www.josuttis.com/libbook/). Here is what he had:

class MyRandom {
public:
ptrdiff_t operator() (ptrdiff_t max) {
double tmp;
tmp = static_cast<double>(rand())
/ static_cast<double>(RAND_MAX);
return static_cast<ptrdiff_t>(tmp * max);
}

};I adapted it as follows:
struct RandomNumberGenerator
{
ptrdiff_t operator() (ptrdiff_t diffVal)
{
struct timeval tod;
gettimeofday(&tod, 0);
srand(tod.tv_sec + tod.tv_usec);
int randVal = rand();

double retVal;
retVal = static_cast<double>(randVal) /
static_cast<double>(RAND_MAX);
return static_cast<ptrdiff_t>(retVal * diffVal);
}

};Now here's the funny part. If I don't divide retVal by
static_cast<double>(RAND_MAX), I am getting a core dump.

Any ideas what could be causing this?

A simple program that operates on a text file and randomly shuffles its
lines follows. I am able to reproduce the coredump with this simple
program
If you want help the FAQ stipulates that you should post a minimal
functional example, however I could not get your example working
without modifications. There were at least two problems with your code,
first <sys/time.his a non-standard header that does not exist on my
system, second you need to include <algorithm>. After some
modifications I was able to compile and run the program, however I did
not get any errors, so either my modifications removed the problem or
it's something specific to your platform/environment.

I suggest that you try again to minimize the problem using only
standard code, you might want to have a look at <ctime>, you could also
put the #ifdef/#else/#endif just around the code-line that differs
instead of the whole body of the function.

--
Erik Wikström

Dec 18 '06 #2

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

Similar topics

1
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...
3
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...
1
by: steflhermitte | last post by:
Dear cpp-ians, I want to apply a stratified sampling on an image. Following simplified example will explain my problem. The original image I with nrows and ncols is now a vector V of length...
70
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...
5
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...
104
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...
12
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...
8
by: Miktor | last post by:
I'm trying to write a lottery number generator for the uk national lottery. Any clues where I'm going wrong? #include <cstdlib> #include <iostream> using namespace std; int main ()
11
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...

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.