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 6 2238
<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 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("A rgument 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
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
>> 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
<ChasW> wrote in message news:i7******** *************** *********@4ax.c om... 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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 nothing. can anyone see how
to make this so it always selects something.
|
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 try to
match up.
I attempted to modify this so it is a 8x8 grid with 16 pairs of
images. The only problem is that only some random tiles seem to be
placed and not all of them.
Heres the original start part of the code:
|
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 compare function to decide
your winnings. I am using Microsoft's C++ version 6 standard, the program
is as follows:
/* * * * * * * * * * * * * * * * * * * *
* *
* Lottery Simulation By Sam...
|
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)
{
srand(time(NULL));
int range = b-a+1;
int x = (rand())%range;<-- problem occur here
int result = a+x;
|
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 library, which is based on GTK. Depending on which
libraries I link in, I can have either a GTK1 or GTK2 user interface.
I'm finding that the simulation behaves differently depending on whether I
link with GTK1 or GTK2.
| |
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 calculations and stores elements in a list. After
that, a sorting algorithm is used over that list.
Two functions are called before the sorting process:
|
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 successfully.
The problem is when I try to hook up a HyperLinkField it's not working.
Basically, what I want to end up with is to have the file name listed in the
column and have the link point to the full file path, for each file in the
list. I've been...
|
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))
|
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 >Verification Image:</span>
<span ><img src="captcha.php" id="captcha" />
<a href="#renew" onclick="javascript: document.getElementById('captcha').src = 'captcha.php?' + Math.random();">refresh</a> </span>
|
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...
|
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...
| |
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...
|
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 project—planning, coding, testing, and deployment—without 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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |