1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public List<double> GenerateLogNormalDistribution(int numberOfTimes, double mean, double standardDeviation) { Random randomGenerator = new Random(); var randomNumbers = from theNumbers in Enumerable.Range(1, numberOfTimes).Select (x => randomGenerator.Next(1, 1000)/1000.0) select theNumbers; randomNumbers.ToList().ForEach(result => Console.WriteLine(result)); List<double> results = new List<double>(); randomNumbers.ToList().ForEach (x => results.Add(mean + (standardDeviation * (Math.Sqrt(-2 * Math.Log(x)) * Math.Cos(6.28 * x))))); return results; }
Refactorings
No refactoring yet !
Jonathan
January 29, 2008, January 29, 2008 22:43, permalink
I refactored my own code... Here your go (only one loop now instead of two)
1 2 3 4 5 6 7
public IEnumerable<double> GenerateLogNormalDistribution(int numberOfTimes, double mean, double standardDeviation) { Random random = new Random(); return from number in Enumerable.Range(1, numberOfTimes) let x = (random.Next(1,1000)/1000.0) select mean + (standardDeviation * (Math.Sqrt(-2*Math.Log(x)) * Math.Cos(2.28*x))); }
Is there a better way to do this? I am not sure, but there must be a way to do this without generating two lists.
Jonathan Starr