Skip to content

Instantly share code, notes, and snippets.

@al2o3cr
Created March 3, 2013 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save al2o3cr/5073866 to your computer and use it in GitHub Desktop.
Save al2o3cr/5073866 to your computer and use it in GitHub Desktop.
Silly SQL trick: computing pi very very inefficiently

Inspired by Postgres: The Bits You Haven't Found:

\set n 1000;

SELECT 4*COUNT(DISTINCT(x, y))/(1.0*:n*:n) AS result FROM generate_series(0,:n) AS x, generate_series(0,:n) AS y WHERE x*x + y*y <= :n*:n;

This uses the simple method of checking every integer-valued point in [0,n] x [0,n] to see if it's inside the circle - the Wikipedia approximations to pi article has more details.

result will converge (very slowly) to the correct value of pi. The O(n^2) behavior of this algorithm doesn't help either.

Interestingly, Postgres appears to construct the result iteratively, as even large values of n don't require additional memory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment