I have a function that computes a binomial distribution naively as follows
CREATE OR REPLACE FUNCTION random_binomial(n int, p float)
RETURNS int AS $$
DECLARE
-- Loop variable
i int;
-- Result of the function
result float = 0;
BEGIN
IF n <= 0 OR p <= 0.0 OR p >= 1.0 THEN
RETURN NULL;
END IF;
FOR i IN 1..n LOOP
IF random() < p THEN
result = result + 1;
END IF;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql STRICT;
While doing simulations I need to call the function thousands of times and this makes the process quite slow. Is there a smarter way to compute a binomial distribution in postgreSQL?