views:

656

answers:

5

I am using a System.Random object which is instantiated with a fixed seed all thoughout the application. I am calling the NextDouble method and after some time passed I am getting 0.0 as result.

Is there any remedy to this, has anyone else encountered this ?

EDIT: I have one seed for the whole run which is set to 1000 for convience sake. The random.NextDouble is called several hundred thousand times. It is an optimizer application and could run for couple hours, but this actually happens after 10-0 mins of execution. I have recently added little bit more random calls to the app.

+7  A: 

How often are you seeding Random? It should be done only once at the start of the program.

And once seeded with a given value, it will always produce the exact same sequence.

James Curran
I am seeding it once.
Tomas Pajonk
+1  A: 

have a look at this http://msdn.microsoft.com/en-us/library/system.random.aspx it should explain why your getting the same value.

Hath
The new Random(DateTime.Now.Second) option is limited to 60 distinct runs of values.
Jason Z
Why not just use the default constructor, and let it pick a seed for you? Guaranteed to be a better idea than _these_.
Domenic
yep ok, changed to be less stupid.
Hath
+8  A: 

The random number generator in .NET is not thread safe. Other developers have noticed the same behaviour, and one solution is as follows (from http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx):

class ThreadSafeRandom
{
    private static Random random = new Random();

    public static int Next()
    {
       lock (random)
       {
           return random.Next();
       }
    }
}
e.James
It is called from different threads !
Tomas Pajonk
+2  A: 

Tomas, I ran into this "bug" before and the solution for me was to make the _rnd variable module-level:

Private Shared _rnd As System.Random()
Public Shared Function RandRange(ByVal low As Integer, ByVal high As Integer) As Integer
    If _rnd Is Nothing Then
        _rnd = New System.Random()
    End If
    Return rnd.Next(low, high)
End Function
Gordon Bell
+1  A: 

Hi,

Other folks have already done a decent job explaining it and providing solutions.

Anyway, a similiar question has been answered before by Erik, check it out:

Pseudo Random Generator with same output

You also get more questions and answers related to the topic (Random Number Generators) at:

Stackoverflow.com random-number-generator

Gene

P.S. This is just to supplement the accepted answer.

GeneQ