0

I wrote a function A, and inside this function there is below code piece.

rnd.Next(1,3);

If I run my A function hundred times, and print out the results, results are not realistic for example it is always win or always lose. So the random function is problematic. I need a realistic real random function.

How to achieve that ?

HOY
  • 1,067
  • 10
  • 42
  • 85

2 Answers2

2

I guess you've done a typical error with Random, you're re-creating it each time i.e:

  Random rnd = new Random();
  int toss = rnd.Next(1,3);

If you do this, rnd could well start each time from the same seed and that's why the result is badly skewed. The solution can be something like that:

   // Let it be thread-safe
   private static ThreadLocal<Random> s_Gen = new ThreadLocal<Random>(
    () => new Random());

   // Thread-safe non-skewed generator
   public static Random Generator {
     get {
       return s_Gen.Value;
     }
   }

   ...

   int toss = Generator.Next(1,3);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

Use this

int i = rnd.Next(int.MaxValue) % 2;

Then have a check whether i = 0 or i = 1.

EDIT Yes, as Dmitry Bychenko mentioned do not instantiate a new Random object each time.

Community
  • 1
  • 1
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58