Advent of 2026, Day 06 – T-SQL Math – Monte Carlo estimation of PI

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In this Microsoft MSSQL T-SQL Math series:

  1. Dec 01: Fibonacci sequence
  2. Dec 02: Factorial numbers
  3. Dec 03: Prime numbers
  4. Dec 04: Prime factorization
  5. Dec 05: Greatest Common Divisor (GCD) and Least Common Multiple (LCM) in T-SQL

Estimating number PI using Monte Carlo method using random numbers is a great illustrator of the relationship between sample size, the estimate of number pi, and the errors in the estimate.

Idea

The Monte Carlo method generates random points inside a square and counts the number of points that fall inside circle inscribed in the square. So this technique is using randomness and statistics.

Number PI is the ration between a circle’s circumference and its diameter and the approximate value is 3.14159265358. And the question is, how can we estimate PI without directly calculating the circumference or builtin logic? We will use geometric idea.

Imagine a square with sides of length 2. Inside this square, we draw a circle with radius 1.

Area of a square is:

Asquare=2×2=4A_{square} = 2 \times 2 = 4

And the area of a circle is:

Acircle=π×12=πA_{circle} = \pi \times 1^2 = \pi

Ratio between the circle’s area and the square’s area is:

AcircleAsquare=π4\frac{A_{circle}}{A_{square}} = \frac{\pi}{4}

where Number PI is:

π=4×AcircleAsquare\pi = 4 \times \frac{A_{circle}}{A_{square}}

and this is the formula for our estimation with Monte Carlo method. We will randomly generate thousadns of points in square and some of the points will land inside the circle, and other will land outside it.

With the formula above, we are estimating PI using random points. For the better understanding this is the scatterplot (using R language) to show the simplicity of calculation. The red line is the circle and the above is the PI estimation.

And the R code to draw this simulation is:

set.seed(2908)
estimate_pi <- function(nof_samples){
  x <- runif(nof_samples, -1,1)
  y <- runif(nof_samples, -1,1)
  num_inside <- sum(x^2 + y^2 <= 1)
  PI_est <- 4 * num_inside / nof_samples
  return(PI_est)
}

nof_samples <- 3000
pi_estimate <- estimate_pi(nof_samples)

x <- runif(nof_samples, -1,1)
y <- runif(nof_samples, -1,1)

plot(x,y, pch=20, col = "black", main = sprintf("Estimate of number PI: %.5f", pi_estimate), xlab = "", ylab = "")
t <- seq(0, pi/2, length.out = 100)
lines(cos(t), sin(t), col = "red", lwd =2)

Why is this interesting?

Monte Carlo simulation is widely used to model uncertainty. For example, we can simulate thousands of possible outcomes to estimate e.g.: financial risk, delivery times, costs of a project, outcomes of business scenarios and many more. With simulations we can estimations many mathematical and physical quantities, model complex systems, evaluate how uncertainty in input parameters can affect the system and many more.

Monte Carolo Estimation of PI in T-SQL

Algorithm we use in T-SQL follows the logic of calculation:

  1. generate random X and Y coordinates between -1 and 1
  2. Check for each point if it is inside the circle
  3. Count the points inside the circle
  4. Divide that count by the total number of generated points.
  5. Multply the result by 4.

The equation for the circle is:

x2+y2=r2x^2 + y^2 = r^2

and with the circle’s radius of 1, a point is inside or on the circl if:

x2+y2≤1x^2 + y^2 \leq 1

For example:

  • Point (0.2, 0.4) is inside the circle, because 0.2*0.2 + 0.4*0.4 = 0.2
  • Point(0.8, 0.8) is outside of the circle, because 0.8*0.8 + 0.8*0.8 = 1.28

So finally, we have the T-SQL calculation:

-- MONTE CARLO Method for estimation PI

DECLARE @N INT = 100000;

;WITH RandomPoints AS (
	SELECT 
	2.00 * r.x - 1.00 AS x
	,2.00 * r.y - 1.00 AS y
	FROM generate_series(1, @N) AS s
	CROSS APPLY
	(
	 SELECT
	   RAND(CHECKSUM(NEWID())) AS X
	   ,RAND(CHECKSUM(NEWID())) AS Y
	) AS r
)
SELECT
COUNT_BIG(*) AS TotalPoints
,SUM( CASE WHEN x*x + y*y <= 1 THEN 1 ELSE 0 END) AS PointsInsideCircle
,CAST(4.0 AS FLOAT)*SUM(CASE WHEN  x*x + y*y <= 1 THEN 1 ELSE 0 END)/COUNT_BIG(*) AS EstimatedPI
FROM RandomPOints

Accuracy and error estimations

The solution should give us a better estimated number of PI with every additional point to the sample. Yet, Monte Carlo gives us a statistical convergence rate, and a typical error decreases proportionally to:

1N\frac{1}{\sqrt N}

wheree N is a sample size. Meaning if we want to reduce the typical error by half, we need to have approximately four times as many samples.

Generating more samples improves the statistical reliability of out estimates, but getting significantly more accurate results can become computationally expensive (which can also be a trade off).

Therefore, in T-SQL there is a PI function built-in as part of the family of mathematical functions.

--default PI
SELECT PI()
-- 3.14159265358979


--PI with higher accuracy
SELECT CAST(PI() AS DECIMAL(38,37))
-- 3.1415926535897931159979634685441851616

As always, the complete code is available on Github : Math T-SQL.

Tomorrow we will check how to write random walks in T-SQL.

Happy coding!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)