SQL to calculate PI using Nilakantha Series

On the Pi Day, I wrote a SQL to calculate PI(π) with accuracy upto 10 decimal digits using Nilakantha Series. When I shared it with my friends on Twitter and Whatsapp, many of them suggested me write a post on it.

As per Wikipedia, The calculation of PI(π) was revolutionized by the development of infinite series techniques. The first written description of an infinite series that could be used to compute PI(π) was laid out in Sanskrit verse by Indian astronomer Nilakantha Somayaji in his Tantrasamgraha, around 1500 AD. Nilakantha Series converges more quickly which means that we need to work out fewer terms to become closer to Pi(π).

Nilakantha Series is described as
Pi(π) = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...


Now lets write the SQL to calculate PI(π) with accuracy upto 10 decimal digits using Nilakantha Series, which is actually very simple -

Step 1: Generate a series of Even Numbers -
ngarg> select rownum*2 rn from dual connect by level <= 5;
        RN
----------
         2
         4
         6
         8
        10

Step 2: Generate each term of divisor in series e.g. (2*3*4), (4*5*6) and so on...
ngarg> with t as
  2  (select rownum*2 rn from dual connect by level <= 5)
  3  select rn a, rn+1 b, rn+2 c, rn*(rn+1)*(rn+2) val from t;
         A          B          C        VAL
---------- ---------- ---------- ----------
         2          3          4         24
         4          5          6        120
         6          7          8        336
         8          9         10        720
        10         11         12       1320

Step 3: Final Step add all the constant values 4 (dividend), SUM all the series and add 3 at end.
ngarg> with t as
  2  (select rownum*2 rn from dual connect by level <= 1500)
  3  select
  4  to_char(3 +
  5    sum(
  6      (decode(mod(rownum,2),0,-1,1) *
  7        4/((rn)*(rn+1)*(rn+2))))
  8    ,'9.9999999999'
  9  ) pi
 10  from t;
PI
-------------
 3.1415926535

Few points on above step, 
- I calculated 1500 terms to make PI value accurate till 10 decimal digits.
- I have used to_char(val,'9.9999999999') to print the value in 10 digits format after decimal.

I hope you have enjoyed this post :)

Related Posts: 
- SQL Interview Question Answers
- Calendar of Current Year by SQL
- Graph Shortest Path Solution by SQL
- Diamond Shaped Star Pattern by SQL
- Oracle: Some Important Date Queries
- Playing With Truncate and Date