Normal distribution: generation algorithm
See original GitHub issueI’ve been using functions RandomNormal
from DataGen.cs
and Population
from Population.cs
in order to visualize the distribution of a given variable
https://github.com/ScottPlot/ScottPlot/blob/0be0921e508656e19323642974a8c5d441bc686a/src/ScottPlot4/ScottPlot/Statistics/Population.cs#L40-L44
I’m no expert whatsoever in statistical algorithms, but it seems that both functions make use of RandomNormalValue
where some kind of Box-Muller algorithm is implemented to generate gaussian numbers:
However, the gaussian data generated seems to be sistematically underestimated as shown below, where the grey vertical line represents the mean and the bell curve appears to be slightly offsetted to the left.
There’s an article in Wikipedia where the Box-Mueller algorithm is explained. It states that Suppose U1 and U2 are independent samples chosen from the uniform distribution on the unit interval (0, 1).
Since Random.NextDouble()
does in fact return the value 0, the current computation of both u1
and u2
will eventually return some 1s.
Therefore, I’ve been using the following modification of RandomNormalValue
:
public double SampleGaussian(Random random, double mean, double stdDev)
{
double u1 = NextDouble(random);
double u2 = NextDouble(random);
double y1 = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); // Math.Cos is also fine
return mean + stdDev * y1;
double NextDouble(Random random)
{
return ((double)random.Next(1, Int32.MaxValue)) / Int32.MaxValue; // random.Next includes 1 and exludes Int32MaxValue
}
}
This modification provides a more visually mean-centered gaussian curve:
Issue Analytics
- State:
- Created a year ago
- Comments:9 (9 by maintainers)
Top GitHub Comments
My bad @bclehmann! I totally messed the whole comments/review options. I’ll pay more attention the next time. Anyways, it’s good to see that @swharden already merged it.
Ah, since it says “Pending” it means it was part of a review, and it looks like you didn’t complete the review (there’s a menu with “Approve”, “Request Changes”, and “Reject” that you have to click on). Alternatively, you can leave a comment without starting a review, and then the comment will be applied immediately.
At any rate thank you for noticing that, I guess I was a little bit on autopilot 😕