473,322 Members | 1,259 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,322 software developers and data experts.

problem with rand()

given the following example:

Using gcc, this compiles, runs, and outputs as expected, but on
vc++.net 2003, the first number is always the same despite the time
seed.

#include <ctime>
#include <iostream>

using namespace std;

// output 10 numbers ranging from [0, n)
int main ()
{
srand((unsigned int)time(NULL));

int n = 100;

for (int i = 0; i < 10; ++i)
{
cout << int(double(rand()) * n / (RAND_MAX + 1.0)) << "\n";
}
cout << endl;

return 0;
}

What am i doing wrong?
Charles

Jul 22 '05 #1
6 2207
<ChasW> wrote...
given the following example:

Using gcc, this compiles, runs, and outputs as expected, but on
vc++.net 2003, the first number is always the same despite the time
seed.

#include <ctime>
#include <iostream>

using namespace std;

// output 10 numbers ranging from [0, n)
int main ()
{
srand((unsigned int)time(NULL));

int n = 100;

for (int i = 0; i < 10; ++i)
{
cout << int(double(rand()) * n / (RAND_MAX + 1.0)) << "\n";
}
cout << endl;

return 0;
}

What am i doing wrong?


First, let me say that it is quite possible that on some hardware RAND_MAX
cannot be represented precisely as a double making it impossible to add 1.0
to it with any effect. But that's really not the problem.

You're scaling your numbers and throwing away the lower part, which _does_
differ from run to run even on VC++. Just print out 'rand()' instead.

It seems that the implementation of the pseudo-random number generator in
the C library shipped with VC++ is rather poor. Try finding a better one
on the Web, it shouldn't be that hard.

Victor
Jul 22 '05 #2
You're scaling your numbers and throwing away the lower part, which _does_
differ from run to run even on VC++. Just print out 'rand()' instead.

It seems that the implementation of the pseudo-random number generator in
the C library shipped with VC++ is rather poor. Try finding a better one
on the Web, it shouldn't be that hard.

Victor


I see what you mean. When i print out just the rand(), the first of
ten calls is very similar each time the program is run, but it _is_
different as you say. It almost makes me want to wrap rand() and
discard the first number each time it is called, but I shouldnt have
to do that.

This is really an odd problem for VC++.

It seems to also affect this wrapper function as well, which is taken
from Koenig's Accelerated C++.

I realize this code can be somewhat costly timewise, but it did
provide a simple function for improving number distribution.

int nrand(int n)
{
if (n <= 0 || n > RAND_MAX)
throw domain_error("Argument to nrand is out of range");

const int bucket_size = RAND_MAX / n;
int r;

do { r = rand() / bucket_size; }
while (r >= n);

return r;
}

I didnt need to look on the Web, Stroustrup's book has one, but until
now, I havent had to use it.

Cheers,
Charles
Jul 22 '05 #3
ChasW wrote:
I see what you mean. When i print out just the rand(), the first of
ten calls is very similar each time the program is run, but it _is_
different as you say. It almost makes me want to wrap rand() and
discard the first number each time it is called, but I shouldnt have
to do that.

This is really an odd problem for VC++.


I had come to this problem myself, and my quick solution was to omit the
first two calls of rand().

Another system dependent solution is to use a Rand object of .NET. It is
far better than their rand() implementation.


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #4
>>
This is really an odd problem for VC++.

I had come to this problem myself, and my quick solution was to omit the
first two calls of rand().


My issue was with the first call only, and only after setting a time
seed.

An easy solution is to just call rand() one time after calling
srand(). Think of it as a "warm-up"

Another system dependent solution is to use a Rand object of .NET. It is
far better than their rand() implementation.


Stroustrup's random number generator also is quite suitable for my
needs and is portable.

Charles
Jul 22 '05 #5

<ChasW> wrote in message news:i7********************************@4ax.com...
You're scaling your numbers and throwing away the lower part, which _does_differ from run to run even on VC++. Just print out 'rand()' instead.

It seems that the implementation of the pseudo-random number generator in
the C library shipped with VC++ is rather poor. Try finding a better one
on the Web, it shouldn't be that hard.

Victor


I see what you mean. When i print out just the rand(), the first of
ten calls is very similar each time the program is run, but it _is_
different as you say. It almost makes me want to wrap rand() and
discard the first number each time it is called, but I shouldnt have
to do that.

This is really an odd problem for VC++.


Actually the problem is not odd at all, neither for VC++ nor other rand()
implementations. In general random number generation is a very subtle
problem and many generators suffer from different defects. What you can do
is to use a "warm-up" phase of the generator, which is a common approach
used in some Monte Carlo simulations. Otherwise you could resort to a
"better" generator (without going into details what better means in this
context) like a Mersenne Twister or ran2 from Numerical Recipes. The code
you gave is already an improvement regarding uniformity of the distribution,
but it has runtime drawbacks because its a simple rejection method.

Regards
Chris


Jul 22 '05 #6
ChasW wrote:
This is really an odd problem for VC++.

I had come to this problem myself, and my quick solution was to omit the
first two calls of rand().

My issue was with the first call only, and only after setting a time
seed.

Yes I am talking about the same case, after a call to srand(time(0));

My experiments showed me that after omitting the first two calls of
rand() after srand(), would improve things (and not one call).


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #7

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

Similar topics

4
by: noone | last post by:
hello all. I am using this code to randomly select one value from an array. srand (); $rec = array("1","2","3","4","5","6"); $rec = $rec; print $rec; problem is, is sometimes it returns...
3
by: MaKiT | last post by:
I have a program which on start makes a 4x4 grid of tiles. These tiles are all blank. Two Array variables hold the position of 8 pairs of images. Then when you click a tile it is uncovered and you...
10
by: sam | last post by:
hi, i am new to C/C++ and have just finished a program based on the UK national lottery, where you enter 6 numbers, six are generated by the computer and there are appropriate messages and a...
6
by: Sen-Lung Chen | last post by:
Dear All: I have a question about this below function.The purpose of this function is to generate one number between a and b. -------------------------- int gennum(int a, int b) {...
7
by: Chris Gordon-Smith | last post by:
I have a simulation program that calls the rand() function at various points while it executes. For the user interface that displays statistics etc. while the program runs, I use the Lazarus GUI...
7
by: Fernando Barsoba | last post by:
Hi, After following the advice received in this list, I have isolated the memory leak problem I am having. I am also using MEMWATCH and I think it is working properly. The program does some...
8
by: =?Utf-8?B?TWlrZSBSYW5k?= | last post by:
I am trying to get a list of files from a specified directory using the System.IO namespace classes, and then use that list as the datasource for a GridView. I have been able to do this...
10
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
10
by: jeddiki | last post by:
Hi, I have a captcha script which should pick up a background image and add some random letters to it and re-display This is the part of the form that the captcha image is part of: <span...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.