To find the area of a unit circle by Monte Carlo integration.

 To find the area of a unit circle by Monte Carlo integration.






Python Code:


# --------------------------------------------------------------------
# Exp -7: To find the area of a unit circle by Monte Carlo integration
# --------------------------------------------------------------------
import numpy as np
import matplotlib . pyplot as plt
import random
def in_circle ( x_pos , y_pos ):
  # Setting radius to 1 for unit circle
  radius = 1
  return x_pos **2 + y_pos **2 < radius **2
# -------------------------------------------------------------------
# function to integrate a unit circle to find pi via monte_carlo
def monte_carlo (n) :

  pi_count = 0

  xli = [ None ]* n
  yli = [ None ]* n
  j = 0
  xlo = [ None ]* n
  ylo = [ None ]* n
  k = 0

  for i in range (1 , n +1 ,1) :
    point_x = random . uniform ( -1.0 ,1.0)     # random . random ()
    point_y = random . uniform ( -1.0 ,1.0)     # random . random ()

    if ( in_circle ( point_x , point_y ) ):
      xli [j] = point_x ; yli [j] = point_y ;
      j +=1
      pi_count += 1
    else :
      xlo [k] = point_x ; ylo [k] = point_y ;
      k +=1
    
# ----------------------- ploting data ------------------------------------
  fig = plt . figure () ; ax = fig . add_subplot (111)
  plt . plot ( xli,yli,'yo',xlo,ylo,'ko',markersize =1)
  plt . xlim ( -1 ,1) ; plt . ylim ( -1 ,1)
  ax . set_aspect ('equal', adjustable ='box')


# -------------------- calculate the ratio --------------------------------

  return 4* pi_count /n


pi = 3.1412
pi_estimate = monte_carlo (10000)
print (" The pi estimate is: ", pi_estimate )
print (" Percent error is: "100 * abs( pi_estimate - pi ) / pi , " %")

#--------- Plotting graph for error and no. of random variables -----------

norc=[]
error=[]
pi = 3.1412
for i in range(1000,10000,1000):
  norc.append(i)
  error.append((monte_carlo(i)-pi)/pi)
fig1 = plt . figure () ; ax = fig . add_subplot (121)
plt.plot(norc, error)
plt.title(' Error with number of random variables ')
plt.ylabel("Error")
plt.xlabel("No. of random variables")
plt.show()













Comments

Popular posts from this blog

Velapanti Python Program

Solving Kepler’s equation by Newton-Raphson method

To find mean , standard deviation and frequency distribution of an actual data set (Python Program)