Tuesday, January 31, 2012

C# Normal density function utils




        ///


        /// Normal density function - Gaussian function
        ///

        ///

        ///

        ///

        ///
        static double NormalDensityFunction(double x, double mean, double stdDev)
        {
            double Z = (x - mean);
            Z = Z * Z;
            Z = -(Z / (2 * stdDev * stdDev));
            double normDist = (1 / Math.Sqrt(2 * Math.PI * stdDev)) * (Math.Exp(Z));
            return normDist;
           // Or
           // return Math.Exp(-(Math.Pow((x - mean) / stdDev, 2) / 2)) / Math.Sqrt(2 * Math.PI) /  stdDev;
        }
     
        ///


        /// Standard normal density function - mean = 0 and stdDev=1
        ///

        ///

        ///
        static double NormalDensityFunctionStd(double Zscore)
        {
            double Z = -(Zscore * Zscore) / 2;
            double normDist = (1 / Math.Sqrt(2 * Math.PI)) * (Math.Exp(Z));
            return normDist;
        }
     
        ///


        /// Cumulative density function of a standard normal (Gaussian) random variable
        /// Area under the normal density function from -inf to x
        ///

        ///

        ///
        static double NormalCDF(double x)
        {          
            const double a1 = 0.254829592;
            const double a2 = -0.284496736;
            const double a3 = 1.421413741;
            const double a4 = -1.453152027;
            const double a5 = 1.061405429;
            const double p = 0.3275911;

            // Save the sign of x
            double sign = 1;
            if (x < 0)
            {
                sign = -1;
                x = x * -1;
            }
            x = x / Math.Sqrt(2.0);

            //A&S formula 7.1.26
            double t = 1.0 / (1.0 + p * x);
            double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.Exp(-x * x);
            return 0.5 * (1.0 + sign * y);
        }
 

Monday, January 9, 2012

Enable / Disable Ping on Windows 2008


Ping is disabled by default on Windows 2008
To enable:
netsh firewall set icmpsetting 8 


To disable:

netsh firewall set icmpsetting 8 disable

Tuesday, January 3, 2012

Json serializer fails for DateTime.MinValue

This cost me so many hours!
The .Net Json serializer ( DataContractJsonSerializer ) fails in certain time zones if you serialize uninitialized DateTime values ie DateTime.MinValue or default(DateTime)


Nice explanation by Nick Martyshchenko here:
http://stackoverflow.com/questions/4025851/why-can-datetime-minvalue-not-be-serialized-in-timezones-ahead-of-utc

You'll probably have the same issue with DateTime.MaxValue in certain time zones.

Workaround: initialize all DateTime values before serialization e.g. to DateTime.MinValue.ToUniversalTime()