473,786 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

oddly behaving rand( ) in microsoft compiler

Hi all,

I'm writing a shell language in c++ that supports the generation of
random numbers, and by its nature, each command must be executed in a
new thread. The call to the random function from my language simply
propogates up to the rand( ) function from c++. For some reason, C++
will give each thread independent use of their own rand( ) function, so
that a rand( ) call from one thread won't affect another thread's call
to rand( ). This meant that every call to random( ) from my language
ended up returning the same number (41, as it happens). To get round
this, I made each thread's constructor call srand on consecutive seeds,
so that the first thread calls srand(1), the next thread srand(2) and
so on. However, the microsoft compiler (but not g++) has more odd
behaviour when generating random numbers from consecutive seeds. In
short, I noticed my calls to random( ) still didn't produce random
numbers. Essentially, I narrowed it down to the following problem:

int main()
{
for(int index=0; index<20; index++){
srand(index);
cout << rand() << endl;
}
return 0;

}

The code above returns the sequence 41, 45, 48, 51, 54, 58, 61, 64,
68....
For some reason, consecutive seeds return closely related numbers on
the first call to rand(). I've tried popping the first rand( ), then
returning the 2nd rand( ) from each seed, but these are still related
(though not quite as strongly as the first calls).

Three questions:
1) Why has it been chosen that each thread gets independent use of
rand( )
2) Why does the microsoft compiler behave like this? Whats the point in
different seeds if they're all related?
3) Any work-arounds anyone can think of?

Thanks a lot :)

Jul 27 '06 #1
4 2797
Hello,

problems with rand() on particular platforms are mildly off-topic here.
The FAQ should say something on the problems of rand(), but seems not
to do so. Absolutely none rand() implementation is a perfect source of
randomness. All I can give are simple quick fixes and keywords for
further reading.

Siam wrote:
Three questions:
1) Why has it been chosen that each thread gets independent use of
rand( )
I can only guess on this question. It is, because it produces less
enough randomness among multiple threads that the program starts
getting deterministic again. In many cases during development and
testing this behaviour is quite useful. Anyway, you cannot take rand()
as something more than just that, the simplest possible source of some
pseudo randomness.

2) Why does the microsoft compiler behave like this? Whats the point
in different seeds if they're all related?
Different seeds producing similar values usually is a sign of a very
poor algorithm for those pseudo random values. If you take poor seeds,
it won't become better. A frequently used strategy involves a strong,
but slow source of randomness to seed a weaker, and faster one.
3) Any work-arounds anyone can think of?
A first try might be better seeds, something involving time() (seconds
since January, 1st 1970) might produce a little bit better results in
your case. At least there is less repetition.

Look at Boost (www.boost.org), they have a set of PRNG (pseudo random
number generator) which are better sources of randomness than most of
the rand() implementations . You have to take resonable seeds to get
good results. However, if you want to know how good your generator has
to be to make an educated choice, then you have to analyze your problem
quite thoroughly. Search with pseudo random number generator or PRNG as
keyword.

Bernd Strieder

Jul 27 '06 #2
"Siam" <si*****@gmail. comschrieb im Newsbeitrag
news:11******** **************@ p79g2000cwp.goo glegroups.com.. .
....
Essentially, I narrowed it down to the following problem:

int main()
{
for(int index=0; index<20; index++){
srand(index);
cout << rand() << endl;
}
return 0;
}

The code above returns the sequence 41, 45, 48, 51, 54, 58, 61, 64,
68....
Don't call srand() for each call to rand() you make. Call srand() only once
per thread (and don't pass 0 to it). Often srand() is called with the result
of time(), i.e. srand(time(0)). Yo will still get similiar sequences in all
threads if they call srand() within a short time, but that's how rand()
works.
Three questions:
1) Why has it been chosen that each thread gets independent use of
rand( )
2) Why does the microsoft compiler behave like this? Whats the point in
different seeds if they're all related?
I can only guess, but since neither C nor C++ know anything about threads,
microsoft is probably free to do so. One reason might be that rand() has to
save some data from one call to another and it is at least faster to save
those data separately for each thread than using some kind of thread
synchronisation . Also, rand() is supposed to produce exactly the same
sequence of pseudo-random numbers when srand() has been called with 0 as its
argument. For a single thread, that would not be possible, if all threads
would share the initial state of rand().#
3) Any work-arounds anyone can think of?
Take a look at the implementation of srand() and rand(). You can easily copy
that code and write your own implementation, where threads share the
internal state of srand() and rand(). ut then you have to synchronize access
to that state.

HTH
Heinz

Jul 27 '06 #3

Heinz Ozwirk wrote:
Don't call srand() for each call to rand() you make. Call srand() only once
per thread (and don't pass 0 to it). Often srand() is called with the result
of time(), i.e. srand(time(0)). Yo will still get similiar sequences in all
threads if they call srand() within a short time, but that's how rand()
works.
Just to clarify, the code I put there isn't from my actual program, it
was to demonstrate my problem with the seeds' random number generation.
In my program, each thread would only call srand() once upon
construction with a unique seed.

I've fixed this problem now, but only by forcing all calls to random
execute on a single thread. Will probably at some stage take a look at
Boost's rand implementations .

Cheers :)

Jul 27 '06 #4
Siam wrote:
>
int main()
{
for(int index=0; index<20; index++){
srand(index);
cout << rand() << endl;
}
return 0;

}

The code above returns the sequence 41, 45, 48, 51, 54, 58, 61, 64,
68....
That's not particularly surprising. Most implementations of rand use a
linear congruential generator, which produces similar values whenever
the previous value was a small integer. Try seeding with 10000*i.
>
Three questions:
1) Why has it been chosen that each thread gets independent use of
rand( )
Most likely, speed. Locking and unlocking a mutex on every call to rand
makes it very slow.
Jul 27 '06 #5

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

Similar topics

3
7110
by: HUNGER | last post by:
HI, I need to generate a long random number upto 4 byte width but my compiler is generating 2 byte int type as RAND_MAX i want to genetrate a rand num like 123456789 that long plz help me.
7
7371
by: eyal.susser | last post by:
I hear rand() is not thread safe. I was using it, foolish man that I am. But what is meant exactly by unsafe? What can happen? Bizzare results from rand()? Something worse? Thanks, Eyal.
36
7139
by: Ben Justice | last post by:
For a program in c, I need some random numbers for a system were people are placing bets. This is not a commerical project btw. Generally, I tend to rely on things from the standard library, because they're written by people with skills far above mine. Hence, I've always used rand() and FALSELY assumed it could produce unpredictable random numbers and could be used in many situations even if security was an issue. Firstly, lets assume...
2
5468
by: Kristofer Berggren | last post by:
Hi, I'm developing a simple application which uses rand() frequently, and I was just wondering if there are any alternatives to generating random numbers other than the in-built function in C? I'm using GNU C/C++ compiler 3.3.1. rand() works okay for me, but I suppose it has its limitations? /Kristofer
36
2695
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
4
3484
by: Skybuck Flying | last post by:
Hi, What is the implementation of rand() on say visual c/c++ 5 or 6 ? Another question... is this rand() implementation the same on any other platforms/compilers/libraries ? Where can I find/look at the implementation of rand() ? Thx for any help.
4
5761
by: Bill Burris | last post by:
Hi, With VS .NET 2003 the rand() function sometimes returns a number equal to RAND_MAX. The docs say: The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. Does this mean that 0 & RAND_MAX are included in the range? I am asking because I was using code from a book, which was developed on Linux. The program occasionally dies, because the random number is used in calculating an array index. It seems that the...
13
3670
by: Spiros Bousbouras | last post by:
The standard says that rand() should return a pseudo-random number but what does pseudorandom mean ? If an implementation of rand() always returned the same number would it be conforming ? What if it always alternated between 2 values ? On the practical side do you have any thoughts on what one could realistically expect from the behaviour of rand() ? Could for example one expect that eventually any value in the range will be returned ?
15
3946
by: Rich Fife | last post by:
Quick rand() question: I know you're not supposed to use "rand() % 1024" for instance, because it focuses on the lower bits. However, it seems to me that given that the argument is not a power of two (or near a power of two), that this is not an issue. The upper bits will participate equally in the result with the lower. Am I missing something? Thanks!
0
9647
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9491
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
10163
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
9959
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
6744
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();...
0
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
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
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.