Random number In C# [duplicate]
Possible Duplicate:
Random number generator not working the way I had planned (C#)
I created a method that returns me a random number:
public static int SelectRandomMachine(i开发者_StackOverflow社区nt max)
{
int seed = (int)DateTime.Now.Ticks;
Random rndNumber = new Random(seed);
int randMachine = rndNumber.Next(0, max);
return randMachine;
}
if I call the method two times, currently it's return me the same random number:
randM1 = SelectRandomMachine(maxNumber);
randM2 = SelectRandomMachine(maxNumber);
any suggestion would be highly appreciated.
Hint look at this line:
int seed = (int)DateTime.Now.Ticks;
If you execute that line twice in quick succession, what do you think the values will be?
For example:
int seed1 = (int)DateTime.Now.Ticks;
int seed2 = (int)DateTime.Now.Ticks;
// Write it out *after* executing; console output can take a while
Console.WriteLine(seed1);
Console.WriteLine(seed2);
See my article on randomness for solutions and more information.
EDIT: Here's a quick and dirty example of the lack of thread safety causing problems:
using System.Collections.Generic;
using System.Threading;
class Program
{
const int Iterations = 1000000;
static readonly Random rng = new Random();
static void Main(string[] args)
{
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 8; i++)
{
Thread t = new Thread(ExerciseRandom);
threads.Add(t);
t.Start();
}
foreach (Thread t in threads)
{
t.Join();
}
Console.WriteLine(rng.Next());
Console.WriteLine(rng.Next());
Console.WriteLine(rng.Next());
}
static void ExerciseRandom()
{
for (int i = 0; i < Iterations; i++)
{
rng.Next();
}
}
}
Output on my box:
0
0
0
You need to create a single instance of a Random
object and call it several times.
Since you are basing your seed on time (number of ticks), quick calls in succession will end up generating the same seed value, hence the pseudo-random number generator will generate the same sequence.
Make the Random instance static:
static Random rndNumber = new Random((int)DateTime.Now.Ticks);
public static int SelectRandomMachine(int max)
{
int randMachine = rndNumber.Next(0, max);
return randMachine;
}
You need to have a private static Random() and refer to it to get the random numbers, Jon and Oded are right, you can't call in quick succession.
private static Random _rnd = new Random();
public static int SelectRandomMachine(int max)
{
//int seed = (int)DateTime.Now.Ticks;
//Random rndNumber = new Random(seed);
int randMachine = _rnd.Next(0, max);
return randMachine;
}
Random number generators generate numbers using an algorithm. If you seed the algorithm with the same number, it will generate the same sequence of numbers. This means if you seed the rand with a number each time and then pull the first number of the sequence you will always get the same number. You need to seed the rand once and then use Next()
repeatedly on the same Rand
object.
精彩评论