How reliable is the C# random number generator?

I've been trying to come up with an equation for the Savage Worlds tabletop RPG that would calculate the expected result for a given set of dice. So to test it, I wrote a small console program that "rolls" the given dice (i.e. 2d8) a million times, adds each result to a list, and then prints out the average roll. I remember reading a while back that C#'s Random class is a pseudo-random number generator so I would like to be sure I'm getting a good result instead of being fooled by the random number generator's limitations.

Are there any tricks to improve or trust the randomness of Random? Here's the code:

class ProblemDice { Random random = new Random(); public ProblemDice() { for (int d = 4; d < 13; d += 2) // Type of dice (d4, d6, d8, d10, d12) for (int n = 0; n < 20; n++) // Number of dice GetRolls(n + 1, d); } private void GetRolls(int n, int d) { List<decimal> rolls = new List<decimal>(); for (int i = 0; i < 1000000; i++) rolls.Add(Roll(n,d)); decimal exp = Math.Round(Expected(n, d), 4); decimal avg = Math.Round(rolls.Average(), 4); Console.Writeline(String.Format("{0}d{1}:\t{2}\t{3}",n,d,exp,avg)); } private int Roll(int n, int d) { if (n > 0) { int roll = random.Next(1, d + 1); // Roll all the dice and reroll any dice that are the maximum value return roll + Roll((roll == d) ? n : n - 1, d); } else return 0; } private decimal Expected(int n, int d) { return (decimal)(n * d * (d + 1)) / (decimal)(2 * (d - 1)); } } 

by campbell1373 via /r/csharp

Leave a Reply