Skip to content

Instantly share code, notes, and snippets.

@berdosi
Last active May 31, 2020 12:20
Show Gist options
  • Save berdosi/b16f14d86476ec315817c836149864e0 to your computer and use it in GitHub Desktop.
Save berdosi/b16f14d86476ec315817c836149864e0 to your computer and use it in GitHub Desktop.
PostgreSQL functions to get the n-th pseudorandom number generated by random() based on a given seed.
CREATE FUNCTION pseudorandom(seed DOUBLE PRECISION, n int)
RETURNS DOUBLE PRECISION AS $$
-- Set the seed (optional). When recursing, this is obviously not done.
SELECT CASE WHEN seed IS NOT NULL THEN setseed(seed) END;
-- recurse until counter reaches 0
SELECT CASE WHEN n>0 THEN pseudorandom(NULL, n-1) END;
-- run random() once. When counter reached 0, this will be the returned.
SELECT random();
$$ LANGUAGE SQL;
COMMENT ON FUNCTION pseudorandom IS '
Get 0-based nth pseudorandom number generated by random() with a given seed.
If seed is NULL, then the current seed is used.
';
CREATE FUNCTION pseudorandom_pg(seed DOUBLE PRECISION, n int)
RETURNS DOUBLE PRECISION AS $$
BEGIN
-- Set the seed (optional). When recursing, this is obviously not done.
IF seed IS NOT NULL THEN
PERFORM setseed(seed);
END IF;
FOR i in 0..n-1 LOOP
PERFORM random();
END LOOP;
RETURN random();
END
$$ LANGUAGE plpgsql;
COMMENT ON FUNCTION pseudorandom_pg IS '
Get 0-based nth pseudorandom number generated by random() with a given seed.
If seed is NULL, then the current seed is used.
';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment