Skip to content

Instantly share code, notes, and snippets.

@DeoluA
Last active January 5, 2019 15:53
Show Gist options
  • Save DeoluA/e6e4b24fbb31caf71f70ff0c2a6e6c63 to your computer and use it in GitHub Desktop.
Save DeoluA/e6e4b24fbb31caf71f70ff0c2a6e6c63 to your computer and use it in GitHub Desktop.
JavaScript Implementation of Error Function and Normal Cumulative Density Function
// https://interactive.deolua.com/normal-dist
/*
*@param number x - the value for which the cumulative probability value is desired
*@param number mean_val - the value of the mean of the distribution
*@param number sd_val_sqrd - the value of the SQUARE of the standard deviation of the distribution
*/
var normal_cdf = function(x, mean_val, sd_val_sqrd){
var err_input = (x - mean_val)/(Math.sqrt(2 * sd_val_sqrd));
return ((1/2) * (1 + err_function(err_input)));
};
// want to interact with more distribution and density functions in real time?
// Go here for more: https://interactive.deolua.com
// https://interactive.deolua.com/normal-dist
// This is an implementation of one of the options of Abramowitz and Stegun's approximations:
// https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
/*
*@param number x
*/
var err_function = function(x){
if(x >= 0){
var p = 0.47047, a1 = 0.3480242, a2 = -0.0958798, a3 = 0.7478556;
var t = 1/(1 + (p * x));
var expon_multi = Math.exp(-(x * x));
var erf_result = 1 - ((t*(a1 + t*(a2 + t*(a3)))) * expon_multi);
return erf_result;
}
else return (-err_function(-x));
};
// want to interact with more distribution and density functions in real time?
// Go here for more: https://interactive.deolua.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment