Skip to content

Instantly share code, notes, and snippets.

@x5lcfd
Created September 8, 2018 09:45
Show Gist options
  • Save x5lcfd/a4424226c63a3b5c1b743f4822bcf7be to your computer and use it in GitHub Desktop.
Save x5lcfd/a4424226c63a3b5c1b743f4822bcf7be to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
import time as time
total_random_points = int(input("\nNumber of random points for Monte Carlo estimate value of PI?\n>"))
start_time = time.time()
inside_circle = 0
x_plot_array = np.empty(shape=(1, total_random_points))
y_plot_array = np.empty(shape=(1, total_random_points))
pi_approx = 0
for i in range(0, total_random_points):
x = np.random.rand()
x_plot_array = np.append(x_plot_array, [x])
y = np.random.rand()
y_plot_array = np.append(y_plot_array, [y])
x_squared = x ** 2;
y_squared = y ** 2;
if np.sqrt(x_squared + y_squared) < 1.0:
inside_circle += 1
pi_approx = inside_circle / (i + 1) * 4
print(f"\nApproximate value for PI: {pi_approx}")
print(f"\nDifference to exact value of PI: {pi_approx - np.pi}")
print(f"Percent Error: (approx-exact)/exact*100: {(pi_approx-np.pi)/np.pi*100}%")
print(f"Execution Time: {time.time() - start_time} seconds\n")
# Draw plot
random_points_plot = plt.scatter(x_plot_array, y_plot_array, color='blue', s=0.1)
circle_plot = plt.Circle((0, 0), 1, color='red', linewidth=2, fill=False)
ax = plt.gca()
ax.cla()
ax.add_artist(random_points_plot)
ax.add_artist(circle_plot)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment