/*This script estimates the value of Pi. It does so by calculating

the length of lines between points on a unit circle(x^2 + y^2 = 1).

As the length of the lines approach 0, Pi is calculated with greater

and greater accuracy. Sort of the idea with, if you are always half way

there do you ever get there? The script estimates by connecting points in

the following series.

  i

  1 (-1/1, 0, 1/1)

  2 (-2/2, -1/2, 0/2, 1/2, 2/2)

  3 (-4/4, -3/4, -2/4, -1/4, 0/4, 1/4, 2/4, 3/4, 4/4)

  .

  .

  .

By C. Eric Cashon

*/

USE tempdb

CREATE TABLE CircleCoordinates(

     TableID int IDENTITY,

     Xvalue Float,

     Yvalue Float)

 

CREATE TABLE ValueForPi(

    PiID int IDENTITY,

    EstimatePiValue Float,

    PiValue Float)

 

SET NOCOUNT ON

DECLARE @Numerator Float

DECLARE @Pi Float

DECLARE @X Float

DECLARE @Y Float

DECLARE @Z Float

DECLARE @i Integer

DECLARE @j Integer

SET @i = 1

SET @j = 1

/*You can increase or decrease the loop counter but be

careful! The CircleCoordinates table size increases exponentially!

Be very careful going past 20! Do not run this script

on a production machine! It can eat up hard drive space

and cpu cycles quickly. Not the best solution for estimating pi

but... some fun T-SQL with very little scripting code.

*/

WHILE @i <= 15

 BEGIN

  SET @X = (-1 * (POWER(2,@i)/2))/(POWER(2,@i)/2)

  SET @Z = POWER(2, @i) + 1

 

    WHILE @j <= @Z

     BEGIN

      --Calculate unit circle y value

      SET @Y = SQRT(1 - POWER(@X,2))

      INSERT INTO CircleCoordinates VALUES(@X,@Y)

      SET @Numerator = (((-1 * (POWER(2,@i)))/2) + @j)

      SET @X = @Numerator/(POWER(2,@i)/2)

      SET @j = @j + 1

     END

    --Look at table for small i interations

    --SELECT * FROM CircleCoordinates

    --Estimate Pi by summing the lengths of lines

    SET @Pi = (SELECT SUM(SQRT

                (POWER((T2.Xvalue - T1.Xvalue),2)

                 + POWER((ABS(T2.Yvalue - T1.Yvalue)),2)))

                 FROM CircleCoordinates T1 INNER JOIN CircleCoordinates T2

                 ON T1.TableID = T2.TableID - 1)

   PRINT 'Pi = ' + CAST(@Pi AS varchar(25))

   --Compare to SQL Servers set value of Pi

   INSERT INTO ValueForPi VALUES(@Pi, Pi())

   --Start again half-way there

   TRUNCATE TABLE CircleCoordinates

   SET @i = @i + 1

   SET @j = 1

END

--Show the results

SELECT * FROM ValueForPi

 

--Clean up

DROP TABLE ValueForPi

DROP TABLE CircleCoordinates