C# Normal Random Number
Solution 1
See this CodeProject article: Simple Random Number Generation. The code is very short, and it generates samples from uniform, normal, and exponential distributions.
Solution 2
You might be interested in Math.NET, specifically the Numerics package.
Caveat: The numerics package targets .NET 3.5. You may need to use the Iridium package if you are targeting an earlier version...
Solution 3
Here is some C that returns two values (rand1 and rand2), just because the algorithm efficiently does so. It is the polar form of the Box-Muller transform.
void RandVal (double mean1, double sigma1, double *rand1, double mean2, double sigma2, double *rand2)
{
double u1, u2, v1, v2, s, z1, z2;
do {
u1 = Random (0., 1.); // a uniform random number from 0 to 1
u2 = Random (0., 1.);
v1 = 2.*u1 - 1.;
v2 = 2.*u2 - 1.;
s = v1*v1 + v2*v2;
} while (s > 1. || s==0.);
z1 = sqrt (-2.*log(s)/s)*v1;
z2 = sqrt (-2.*log(s)/s)*v2;
*rand1 = (z1*sigma1 + mean1);
*rand2 = (z2*sigma2 + mean2);
return;
}
Solution 4
This library is pretty good also:
.NET random number generators and distributions
Solution 5
Sorry I don't have any code for you but I can point you to some algorithms on Wikipedia. The algorithm you choose I guess depends on how accurate you want it and how fast it needs to be.
J.Hendrix
My current expertise as a Senior Programmer Analyst is in data driven web applications that support various business needs such as product information, customer relationship management, and transaction processing. I embrace clean intuitive design and emphasize code reusability. I have a strong background in Object Oriented Programming, as well as T-SQL. My language of choice is C# on the server side and JavaScript/jQuery/AJAX on the client side.
Updated on August 14, 2022Comments
-
J.Hendrix over 1 year
I would like to create a function that accepts
Double mean
,Double deviation
and returns a random number with a normal distribution.Example: if I pass in 5.00 as the mean and 2.00 as the deviation, 68% of the time I will get a number between 3.00 and 7.00
My statistics is a little weak…. Anyone have an idea how I should approach this? My implementation will be C# 2.0 but feel free to answer in your language of choice as long as the math functions are standard.
I think this might actually be what I am looking for. Any help converting this to code?
Thanks in advance for your help.