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.
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();
}
}
}
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.
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
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.
have a look at this http://msdn.microsoft.com/en-us/library/system.random.aspx it should explain why your getting the same value.