Question: Use python to: (1) Familiarize with the given code: (i) Inspection of the code (ii) Identify where the missing code is to complete the calculation
Use python to:
(1) Familiarize with the given code:
(i) Inspection of the code
(ii) Identify where the missing code is to complete the calculation of pi
(2) Complete the code to calculate pi
(i) Add a block to count how many points inside the circile
(ii) Play with your code to calculate pi by changing the parameters, i.e., how many points you generate
(iii) Are there any points right on the boundaries?
code to start:
import sys
import numpy as np # an alias for the namespace
import random
import matplotlib.pyplot as plt
#setting MC parameters
NumP=10000 # generate how many random point in side the square
#MC simulation block
pi_all=[]
cordx=[];cordy=[] # initialize the two empty coordinate lists
inside=0
for i in range(0,NumP): #generate random coordinates
cordx.append(random.random())
cordy.append(random.random())
r2 = cordx[i]*cordx[i]+cordy[i]*cordy[i]
# write control to count inside
pit= 4.0*inside/NumP
#End of sampling
pi_all.append(pit)
#print out result
print(' ')
print("pi: ","{:10.6f}".format(pit))
plt.hist(pi_all) # print hist of the sampling
# plot the random pair: cordx,cordy graphically for the last MC simulation
Symbol=10
LineW = 3
Lsp=100
f = plt.figure()
f.set_figwidth(8)
f.set_figheight(8)
plt.xlim(0,1)
plt.ylim(0,1)
plt.xlabel('X Cordinate')
plt.ylabel('Y Cordinate')
plt.scatter(cordx, cordy, s=Symbol,marker='o')
#plot circle
x = np.linspace(0,1,Lsp)
y = np.sqrt(1. - x*x)
plt.plot(x, y,'-r',color='red', linestyle='-', lw=LineW)
plt.show()
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
