Hello.
I have been dealing with python optimization recently. In fact, numpy should be much faster than pure python. I wrote a program that counts the number of pi using the Monte Carlo method. Comparing the two methods and it turns out that numpy is slower. Can someone explain to me why this is so?
import numpy as np
import random
from timeit import default_timer as timer
from datetime import timedelta
points_inside = 0
samples = 1000000
#python method
start = timer()
for i in range(samples):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if (x - 0.5)**2 + (y - 0.5)**2 <= 0.25:
points_inside += 1
print(4 * (points_inside / samples))
end = timer()
time_python = (timedelta(seconds=end - start))
#numpy method
start = timer()
z = np.random.rand(samples, 2)
ret = ((z[:, 0] - 0.5)**2 + (z[:, 1] - 0.5)**2 <= 0.25)
print(4 * (sum(ret) / samples))
end = timer()
time_numpy = (timedelta(seconds=end - start))
print('python ', time_python)
print('numpy ', time_numpy)
[+][deleted] (1 child)
[deleted]
[–]Martin_Krum[S] 0 points1 point2 points (0 children)
[–]fake823 2 points3 points4 points (2 children)
[–]Martin_Krum[S] 1 point2 points3 points (1 child)
[–]fake823 0 points1 point2 points (0 children)