0

The .Net package "MathNet.Numerics.Distributions" contains a method Normal(double mean, double stddev, Random randomSource).

The first two parameters are double which can easily be set. But the third parameter Random randdomSource is causing troubles.

Does anybody know to set it and use it in Normal(double mean, double stddev, Random randomSource)?

TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

1

Try this:

var randomSource = new Random();

It is best practice, though, to only create a single instance of Random in any app - this is to avoid the possibility of creating multiple Random instances that share the same random seed.

So you're best off doing something like this:

public static class Global
{
    [ThreadStatic] public static readonly Random Random = new Random();
}

Then you would call your method like this:

Normal(0.0, 1.0, Global.Random);
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Although it is correct that you need to be careful with your Random instances and their seeds, please don't do that when working with Math.NET Numerics. This will cause you threading problems, and the default behavior of the overloads without random source argument is already handling this in a better way. – Christoph Rüegg Jul 06 '15 at 04:47
  • @ChristophRüegg - What threading problems will this cause? Nonetheless, I've updated my answer to help avoid threading issues. – Enigmativity Jul 06 '15 at 05:23
  • Some of the higher-order functions in Math.NET assume that the provided lambda is a pure function and may call it from multiple threads, e.g. in linear algebra with very large matrices. ThreadStatic would not help when used as part of such a lambda. But thanks for the update! – Christoph Rüegg Jul 06 '15 at 17:24
1

as the others have already answered, use the constructor without that third argument, i.e. Normal(double mean, double stddev).

We recommend the following rules when dealing with random sources and distributions:

  • The random source is only needed for sampling random numbers with the distribution. If you don't need to generate random numbers, don't provide a random source and use the constructor overload without one instead.
  • If you do need to generate random numbers with the distribution, only provide a random source if you do not want to use the default random source for some reason. If the default is fine (essentially a safe wrapper of System.Random), use the constructor overload without one instead
  • Be careful with passing a System.Random instance to Math.NET Numerics. Consider to use SystemRandomSource instead which is thread-safe.

See also:

Christoph Rüegg
  • 4,626
  • 1
  • 20
  • 34