Skip to content

Instantly share code, notes, and snippets.

@ycku
Last active June 4, 2025 13:27
Show Gist options
  • Save ycku/fc23fb98ee7e428c848960e81e5c3826 to your computer and use it in GitHub Desktop.
Save ycku/fc23fb98ee7e428c848960e81e5c3826 to your computer and use it in GitHub Desktop.
NORM.DIST on PostgreSQL
CREATE FUNCTION norm_dist(x real, mean real, stddev real, cumulative boolean) RETURNS real AS $$
DECLARE p real;
BEGIN
IF cumulative = false THEN
SELECT (1 / (stddev * sqrt(2 * pi()))) * exp(-1 * power(x - mean, 2) / (2 * power(stddev, 2))) INTO p;
ELSE
SELECT 0.5 * (1 + erf((x - mean) / (stddev * sqrt(2)))) INTO p;
END IF;
RETURN p;
END;
$$ LANGUAGE plpgsql;
select 1.0-norm_dist(6.0,5.0,1.0,false); -- x在6.0附近的密度(作圖是高度)
select norm_dist(6.0,5.0,1.0,true); -- x<6.0的機率
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment