-
Notifications
You must be signed in to change notification settings - Fork 30
Generate Random Numbers from a Distribution
Every distributions in the Meta.Numerics.Statistics.Distributions namespace has a GetRandomValue method that generates deviates distributed according to the distribution. Here is example code that generates 100 normal deviates:
using System;
using Meta.Numerics.Statistics.Distributions;
Distribution distribution = new NormalDistribution(-1.0, 2.0);
Random rng = new Random(1);
List<double> sample = new List<double>();
for (int i = 0; i < 100; i++) {
double value = distribution.GetRandomValue(rng);
sample.Add(value);
}
Most of the generators use optimized implementations that are extremely fast.
The basis of all non-uniform random number generators is a uniform random number generator (RNG) that generates random numbers between 0 and 1. The .NET Framework's built-in RNG is Random. If you don't want to use built-in RNG, for example because you prefer to an RNG based on the Mersene Twister algorithm, just put your implementation in a class that inherits from Random and override its methods. You can then use Meta.Numerics non-uniform generators on top of your custom Random replacement.
Notice that the constructor of Random takes an integer, called the seed. Given the same seed, the same sequence of deviates will be generated. This is extremely useful in scientific programming, because if you ever run in to a problem you will want to be able to reproduce the inputs that led to it. If your application requires a new sequence each time, use Random's default constructor, which will generate a seed based on the system clock.
No. The Random class itself is not thread-safe, so it doesn't make sense to put a lot of effort into making code built on top of it thread-safe. You could make the whole system thread-safe using locks, but since lock overhead is much greater than the computational effort to generate a random deviate, you are not likely to get the performance boost you wanted from multi-threading with this approach. A better approach is to just give each thread its own instance of Random and the distribution class. Be sure to use a different seed for each Random, or they will all generate the same sequence.
- Project
- What's New
- Installation
- Versioning
- Tutorials
- Functions
- Compute a Special Function
- Bessel Functions
- Solvers
- Evaluate An Integral
- Find a Maximum or Minimum
- Solve an Equation
- Integrate a Differential Equation
- Data Wrangling
- Statistics
- Analyze a Sample
- Compare Two Samples
- Simple Linear Regression
- Association
- ANOVA
- Contingency Tables
- Multiple Regression
- Logistic Regression
- Cluster and Component Analysis
- Time Series Analysis
- Fit a Sample to a Distribution
- Distributions
- Special Objects
- Linear Algebra
- Polynomials
- Permutations
- Partitions
- Uncertain Values
- Extended Precision
- Functions