Skip to content

Instantly share code, notes, and snippets.

@jpcrespo
Created April 24, 2020 04:46
Show Gist options
  • Save jpcrespo/d60c24808b4618980a160aa8d06f93ff to your computer and use it in GitHub Desktop.
Save jpcrespo/d60c24808b4618980a160aa8d06f93ff to your computer and use it in GitHub Desktop.
Uso Monte Carlo para calcular Py con dos bucles
import numpy as np
import matplotlib.pyplot as plt
from time import time
A=[]
N = np.logspace(2,8,num=10,endpoint=True)
N = np.around(N).astype(int) #numeros enteros
tiempo_inicial = time()
#Calculamos los numeros random
for i in N:
count = 0
for j in range(i):
x = np.random.random()
y = np.random.random()
dist = np.sqrt(x**2+y**2)
if dist < 1:
count = count +1
piexp=4*count/i
A.append(np.absolute(piexp-np.pi))
tiempo_final = time()
tiempo_ejecucion = tiempo_final - tiempo_inicial
print('El tiempo de ejecución del programa fue ',tiempo_ejecucion,' segundos')
#generamos la gráfica
plt.figure()
plt.plot(np.arange(1,11),A,'o-')
plt.xticks(range(1,N.size+1), N, rotation=20)
plt.xlabel('Número de pruebas')
plt.ylabel('Error abs Pi por MC')
plt.grid(True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment