
# pierror.py

'''
  PIERROR estimates pi by counting random points in a square.

  The square has area 1, the quarter circle area pi/4.

  Theoretical analyses of the 
  Monte Carlo technique show that the error of the method decreases
  as N^-(1/2), where N is the number of simulations. So, going from
  N = 100 = 10^2 to N = 10,000 = 10^4 (an increase in N by a factor of
  10^2) should reduce the error by a factor of about 10.
  
  Paul Nahin,
  Digital Dice: Computational Solutions to Practical Probability Problems,
  Princeton, 2008,
  Intro p.14
'''

import random, math
import matplotlib.pyplot as plt


NUM_ITERS = 1000
 
numPts = [100, 10000]
for j in range(len(numPts)):
  n = numPts[j]
  ests = []
  errs = []
  for loop in range(NUM_ITERS):
    inCount = 0
    for k in range(n):
      x = random.random()
      y = random.random()
      if (x**2 + y**2 < 1.0):
        inCount += 1
    ests.append(4.0*inCount/n)
    errs.append((4.0*inCount - math.pi*n)*100/(n * math.pi))


  plt.hist(errs)
  plt.xlim(-25, 25)
  plt.xlabel("Percent error")
  plt.ylabel("Number of simulations")
  plt.show() 

  print(f"Using {n} points, estimate is {sum(ests)/NUM_ITERS:.6f}, % error {sum(errs)/NUM_ITERS:.6f}")
