Make sure that empty arrays or arrays with all the same entry return 0 for Skewness and Kurtosis rather than throwing a division by zero error

This commit is contained in:
Stuart Lynn 2015-12-04 14:54:15 -05:00
parent a88bfc51a3
commit 0ecbbd8e71

View File

@ -13,17 +13,21 @@ CREATE OR REPLACE FUNCTION CDB_Kurtosis ( in_array NUMERIC[] ) RETURNS NUMERIC a
DECLARE DECLARE
a numeric; a numeric;
c numeric; c numeric;
s numeric;
k numeric; k numeric;
BEGIN BEGIN
SELECT AVG(e), COUNT(e)::numeric, stddev(e) INTO a, c, s FROM ( SELECT unnest(in_array) e ) x; SELECT AVG(e), COUNT(e)::numeric * power(stddev(e),4) INTO a, c FROM ( SELECT unnest(in_array) e ) x;
EXECUTE 'SELECT sum(power($1 - e, 4)) / ( $2 * power($3, 4)) - 3 IF c=0 THEN
FROM (SELECT unnest($4) e ) x' RETURN 0;
ELSE
EXECUTE 'SELECT sum(power($1 - e, 4)) / ($2 ) - 3
FROM (SELECT unnest($3) e ) x'
INTO k INTO k
USING a, c, s, in_array; USING a, c, in_array;
RETURN k; RETURN k;
END IF;
END; END;
$$ language plpgsql IMMUTABLE; $$ language plpgsql IMMUTABLE;
@ -32,16 +36,18 @@ CREATE OR REPLACE FUNCTION CDB_Skewness ( in_array NUMERIC[] ) RETURNS NUMERIC a
DECLARE DECLARE
a numeric; a numeric;
c numeric; c numeric;
s numeric;
sk numeric; sk numeric;
BEGIN BEGIN
SELECT AVG(e), COUNT(e)::numeric, stddev(e) INTO a, c, s FROM ( SELECT unnest(in_array) e ) x; SELECT AVG(e), COUNT(e)::numeric * power(stddev(e),3) INTO a, c FROM ( SELECT unnest(in_array) e ) x;
IF c=0 THEN
EXECUTE 'SELECT sum(power($1 - e, 3)) / ( $2 * power($3, 3)) RETURN 0;
FROM (SELECT unnest($4) e ) x' ELSE
EXECUTE 'SELECT sum(power($1 - e, 3)) / ( $2 )
FROM (SELECT unnest($3) e ) x'
INTO sk INTO sk
USING a, c, s, in_array; USING a, c, in_array;
RETURN sk; RETURN sk;
END IF;
END; END;
$$ language plpgsql IMMUTABLE; $$ language plpgsql IMMUTABLE;