public static double GetProbability(this Normal nr, double value) { double result = nr.CumulativeDistribution(value); if (value > nr.Mean) { result = 1 - result; } return(result); }
public static List <double> normcdf(List <double> x, double mu, double sig) { List <double> res = new List <double>(); Normal normal = new MathNet.Numerics.Distributions.Normal(mu, sig); for (int i = 0; i < x.Count; i++) { res.Add(normal.CumulativeDistribution(x[i])); } return(res); }
private static double Nu(double x, double tol) { double nu; double lnu0, lnu1, dk, xk; int i, k; // fpnorm(x): pnorm(x, 0, 1, lower.tail=TRUE, log.p=FALSE) // calculates P(X <= x) var norm = new Normal(); // N(0, 1) if (x > 0.01) { lnu1 = Math.Log(2.0) - 2 * Math.Log(x); lnu0 = lnu1; k = 2; dk = 0; for (i = 0; i < k; i++) { dk = dk + 1; xk = -x * Math.Sqrt(dk) / 2.0; lnu1 = lnu1 - 2.0 * norm.CumulativeDistribution(xk) / dk; } while (Math.Abs((lnu1 - lnu0) / lnu1) > tol) { lnu0 = lnu1; for (i = 0; i < k; i++) { dk = dk + 1; xk = -x * Math.Sqrt(dk) / 2.0; lnu1 = lnu1 - 2.0 * norm.CumulativeDistribution(xk) / dk; } k *= 2; } } else { lnu1 = -0.583 * x; } nu = Math.Exp(lnu1); return nu; }
/// <summary> /// Computes the cumulative distribution function of the Student t-distribution. /// </summary> /// <param name="x">The location at which to compute the cumulative density.</param> /// <returns>the cumulative density at <paramref name="x"/>.</returns> public double CumulativeDistribution(double x) { // TODO JVG we can probably do a better job for Cauchy special case if (Double.IsPositiveInfinity(_dof)) { return(Normal.CumulativeDistribution(_location, _scale, x)); } var k = (x - _location) / _scale; var h = _dof / (_dof + (k * k)); var ib = 0.5 * SpecialFunctions.BetaRegularized(_dof / 2.0, 0.5, h); return(x <= _location ? ib : 1.0 - ib); }
/// <summary> /// Run example /// </summary> /// <a href="http://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a> public void Run() { // 1. Initialize the new instance of the Normal distribution class with parameters Mean = 0, StdDev = 1 var normal = new Normal(0, 1); Console.WriteLine(@"1. Initialize the new instance of the Normal distribution class with parameters Mean = {0}, StdDev = {1}", normal.Mean, normal.StdDev); Console.WriteLine(); // 2. Distributuion properties: Console.WriteLine(@"2. {0} distributuion properties:", normal); // Cumulative distribution function Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", normal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000")); // Probability density Console.WriteLine(@"{0} - Probability density at location '0.3'", normal.Density(0.3).ToString(" #0.00000;-#0.00000")); // Log probability density Console.WriteLine(@"{0} - Log probability density at location '0.3'", normal.DensityLn(0.3).ToString(" #0.00000;-#0.00000")); // Entropy Console.WriteLine(@"{0} - Entropy", normal.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain Console.WriteLine(@"{0} - Largest element in the domain", normal.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain Console.WriteLine(@"{0} - Smallest element in the domain", normal.Minimum.ToString(" #0.00000;-#0.00000")); // Mean Console.WriteLine(@"{0} - Mean", normal.Mean.ToString(" #0.00000;-#0.00000")); // Median Console.WriteLine(@"{0} - Median", normal.Median.ToString(" #0.00000;-#0.00000")); // Mode Console.WriteLine(@"{0} - Mode", normal.Mode.ToString(" #0.00000;-#0.00000")); // Variance Console.WriteLine(@"{0} - Variance", normal.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation Console.WriteLine(@"{0} - Standard deviation", normal.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness Console.WriteLine(@"{0} - Skewness", normal.Skewness.ToString(" #0.00000;-#0.00000")); Console.WriteLine(); // 3. Generate 10 samples Console.WriteLine(@"3. Generate 10 samples"); for (var i = 0; i < 10; i++) { Console.Write(normal.Sample().ToString("N05") + @" "); } Console.WriteLine(); Console.WriteLine(); // 4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram Console.WriteLine(@"4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram"); var data = new double[100000]; for (var i = 0; i < data.Length; i++) { data[i] = normal.Sample(); } ConsoleHelper.DisplayHistogram(data); Console.WriteLine(); // 5. Generate 100000 samples of the Normal(-10, 0.2) distribution and display histogram Console.WriteLine(@"5. Generate 100000 samples of the Normal(-10, 0.01) distribution and display histogram"); normal.Mean = -10; normal.StdDev = 0.01; for (var i = 0; i < data.Length; i++) { data[i] = normal.Sample(); } ConsoleHelper.DisplayHistogram(data); }
public PlotModel createNormalPlotModel(VariableDesc oCategVar, VariableDesc oVar) { if (oVar == null) { return null; } var srcData = ComputeVariableCategValues(oCategVar, oVar); if (srcData == null) { return null; } List<ValueDesc> sortedData = new List<ValueDesc>(); List<double> oList = new List<double>(); Dictionary<String, ScatterSeries> oDict = new Dictionary<string, ScatterSeries>(); foreach (var s in srcData.Keys) { oDict[s] = new ScatterSeries(s) { MarkerType = MarkerType.Circle }; var vals = srcData[s]; foreach (var v in vals) { v.StringTag = s; sortedData.Add(v); oList.Add(v.DoubleValue); } }// s sortedData.Sort((v1, v2) => { double d1 = v1.DoubleValue; double d2 = v2.DoubleValue; int nRet = -1; if (d1 > d2) { nRet = 1; } else if (d1 == d2) { nRet = 0; } return nRet; }); int n = sortedData.Count; if (n < 2) { return null; } DescriptiveStatistics st = new DescriptiveStatistics(oList); double mean = st.Mean; double dev = st.StandardDeviation; if (dev <= 0.0) { return null; } var dist = new Normal(); var s2 = new LineSeries { Title = "Distribution normale" }; int nTotal = 1; int i = 0; double dn = (double)n; var oAr = sortedData.ToArray(); ValueDesc vCur = null; while (i < n) { vCur = oAr[i]; double xMax = vCur.DoubleValue; int c = 0; while ((vCur.DoubleValue <= xMax) && (i < n)) { double x = vCur.DoubleValue; double xr = (x - mean) / dev; double yr = dist.CumulativeDistribution(xr); s2.Points.Add(new DataPoint(x, yr)); double yc = (double)nTotal / dn; vCur.DoubleTag = yc; String scateg = vCur.StringTag; if ((!String.IsNullOrEmpty(scateg)) && oDict.ContainsKey(scateg)) { oDict[scateg].Points.Add(new ScatterPoint(x, yc) { Tag = vCur.Index }); } ++i; ++c; if (i >= n) { break; } vCur = oAr[i]; } nTotal += c; }// i PlotModel model = new PlotModel(oVar.Name); foreach (var ss in oDict.Values) { model.Series.Add(ss); } s2.Smooth = true; model.Series.Add(s2); return model; }
private void obtenerFrecuenciasEsperadas() { double media = MathNet.Numerics.Statistics.ArrayStatistics.Mean(datos.ToArray()); switch (distribucionElegida) { case TipoDistribucion.continuaExponencial: /* * En el caso de haber elegido la distribucion exponencial, tenemos que: * * lambda(media) = 1 / (media muestral); * */ //obtenemos el lambda para esta distribucion double lambda = 1 / media; //generamos la distribucion para el lambda dado: Exponential exponencial = new Exponential(lambda); //recorremos los intervalos para obtener los valores minimos y maximos, y asi calcular la frecuencia esperada foreach (Intervalo intervalo in intervalos) { intervalo.frecuenciaEsperada = (exponencial.CumulativeDistribution(intervalo.limiteSuperior) - exponencial.CumulativeDistribution(intervalo.limiteInferior)) * datos.Count(); intervalo.frecuenciaEsperada = Math.Round(intervalo.frecuenciaEsperada, CANTIDAD_DECIMALES); } break; case TipoDistribucion.continuaUniforme: /* * En el caso de haber elegido uniforme, tenemos que: * * FE = cantidad de datos de la muestra / cantidad de intervalos; * */ //Entonces obtenemos este dato y se lo asignamos a todos los intervalos. double frecuenciaEsperada = (double)datos.Count() / (double)intervalos.Count(); foreach (Intervalo intervalo in intervalos) { intervalo.frecuenciaEsperada = frecuenciaEsperada; intervalo.frecuenciaEsperada = Math.Round(intervalo.frecuenciaEsperada, CANTIDAD_DECIMALES); } break; case TipoDistribucion.continuaNormal: /* * Para distribucion normal tenemos: * * desviacion estandar (sigma) = raiz cuadrada de la media; * */ //obtenemos la varianza double varianza = MathNet.Numerics.Statistics.ArrayStatistics.Variance(datos.ToArray()); //calculamos la deviacion estandar double desviacionEstandar = Math.Sqrt(varianza); //creo la distribucion normal MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(media, desviacionEstandar); foreach (Intervalo intervalo in intervalos) { intervalo.frecuenciaEsperada = (normal.CumulativeDistribution(intervalo.limiteSuperior) - normal.CumulativeDistribution(intervalo.limiteInferior)) * datos.Count(); intervalo.frecuenciaEsperada = Math.Round(intervalo.frecuenciaEsperada, CANTIDAD_DECIMALES); } break; case TipoDistribucion.continuaPoisson: double lambdaPoisson = 1 / media; Poisson poisson = new Poisson(media); //recorremos los intervalos para obtener los valores minimos y maximos, y asi calcular la frecuencia esperada foreach (Intervalo intervalo in intervalos) { intervalo.frecuenciaEsperada = (poisson.CumulativeDistribution(intervalo.limiteInferior) - poisson.CumulativeDistribution(intervalo.limiteInferior - 1)) * datos.Count(); intervalo.frecuenciaEsperada = Math.Round(intervalo.frecuenciaEsperada, CANTIDAD_DECIMALES); } break; } }
/// <summary> /// Returns a gaussian weighted average of pixels centred on a point /// </summary> /// <param name="Source"></param> /// <param name="Coords"></param> /// <param name="Radius"></param> /// <returns></returns> public static Color GetGaussianPixel(Bitmap Source, ProportionPoint Coords, int Radius) { if ((Radius > MaxGausRadius) || (Radius < 0)) throw new ArgumentOutOfRangeException("Radius", "Radius must be >= 0 and < MaxGausRadius"); int diameter = 1 + (2 * Radius); int centre = Radius + 1; double sigma = (double)Radius / 2d; Normal dist = new Normal(Radius, sigma); // create new bitmap with known PixelFormat Bitmap bm = new Bitmap(Source.Width, Source.Height, PixelFormat.Format24bppRgb); using (Graphics gr = Graphics.FromImage(bm)) { gr.DrawImage(Source, new Rectangle(0, 0, bm.Width, bm.Height)); } //Source.Dispose(); // Now we know there are 24 bits per pixel. 24 / 8 (bits / byte) = 3 bytes const int BytesPerPixel = 3; Color colourPixel; int x, y; x = (int)Math.Round((double)(Coords.x * (float)bm.Width)); if (x >= bm.Width) x = bm.Width - 1; y = (int)Math.Round((double)(Coords.y * (float)bm.Height)); if (y >= bm.Height) y = bm.Height - 1; int stride; byte[] rgbValues = GetBytesFromImage(bm, out stride); bm.Dispose(); int centrePixel = (Math.Abs(stride) * y) + (x * BytesPerPixel); if (Radius == 0) { // get the RGB data from the byte array colourPixel = Color.FromArgb(0, rgbValues[centrePixel], rgbValues[centrePixel + 1], rgbValues[centrePixel + 2]); } else { // work out where the origin of our sub-region will be int TLcorner = centrePixel - (BytesPerPixel * (Radius + (Radius * stride))); double weightCumulative = 0; double[] rgbCumulative = new double[3] { 0d, 0d, 0d }; for (int row = 0; row < diameter; row++) { for (int col = 0; col < diameter; col++) { // find the start of this pixel int pixelStart = TLcorner + (BytesPerPixel * (col + (row * stride))); int centrePixelStart = pixelStart - (col - Radius); int line = (int)Math.Floor((double)centrePixelStart / (double)stride); // check pixel lies within bound of image if ((pixelStart >= 0) && (pixelStart < rgbValues.Length)) { // check pixel hasn't wrapped to different line int lineOfThisPixel = (int)Math.Floor((double)pixelStart / (double)stride); if (line == lineOfThisPixel) { // work out the distance from the centre of the sub-region int relX = Math.Abs((col + 1) - centre); int relY = Math.Abs((row + 1) - centre); double hyp = Math.Sqrt((double)(Math.Pow(relX, 2)) + (Math.Pow(relY, 2))); // get a gaussian weight for this distance double weight = dist.CumulativeDistribution(Radius - hyp); weightCumulative += weight; // add the weighted RGB values to the array for (int p = 0; p < 3; p++) { rgbCumulative[p] += rgbValues[pixelStart + p] * weight; } } } } } // compose the resulting color pixel byte[] rgbFinal = new byte[3]; for (int p = 0; p < 3; p++) { int final = (int)Math.Round(rgbCumulative[p] / weightCumulative); if (final > 255) final = 255; rgbFinal[p] = (byte)(final & 0xff); } return Color.FromArgb(0, rgbFinal[0], rgbFinal[1], rgbFinal[2]); } return colourPixel; }