PI using WITH RECURSIVE :)

From: Grzegorz Jaśkiewicz pgsql-general(at)postgresql(dot)org PI using WITH RECURSIVE :) 2008-10-08 13:53:35 2f4958ff0810080653s52629bf1tac54255ae5d4ed7d@mail.gmail.com Raw Message | Whole Thread | Download mbox | Resend email 2008-10-08 13:53:35 from Grzegorz Jaśkiewicz pgsql-general

Hey folks,
I waned share, and possibly stick in as an example on how to use WITH
RECURSIVE, little thing that I wrote just to prove that I can understand how
it works.
It calculates PI, algorithm is pretty simple. I'll give you 2 versions. C++
one , and SQL one :D Let me know, what ya think

so here we go.

C++ code:

iterations *= 2;

for (unsigned int i=0; i<iterations; i+=4)-
{
double t1, t2;
t1 = 4.0/(3+i) ;
t2 = 4.0/(3+i+2);

pisub += t1;
}

double ourPi = 4 + piadd - pisub;

SQL:

WITH RECURSIVE t AS
(
select 0::float8 as subs, 0::float8 as adds, 0 as x
UNION ALL
select (4::float8)/(3+x) as subs, (4::float8)/(3+x+2) as adds, x+4 as x
from t where x < 10000
)
select 4::float8 + sum(adds) - sum(subs) from t;