mardi 8 décembre 2020

Creating a numpy array from repeating a function n times with random behavior inside the function without for loops

I am doing optimizations in my code and would like to remove this for loop if possible. I have the following code:

    def f(x):
        return np.pi * x * np.cos((np.pi / 2) * x ** 2)

    def monte_carlo(b, n):
        xrand = np.random.uniform(0, b, (1, n))
        integral = np.sum(f(xrand))
        return b/n * integral

    data = np.array([monte_carlo(b, n) for _ in range(100)])

In this code b is the upper limit (usually between 0 and 16) and n is the number of samples used (usually between 10E4 and 10E7). The monte carlo function is used for a basic monte carlo integration of the integral between 0 and b of the function f(x).

What I'm trying to do is to remove the for loop in data. I know it's not really a performance issue, but my assignment asks to try and do performance optimizations. I'm using a comprehension right now which is a little faster than a normal for loop but I think there's more optimization that can be done, pythons for loops are rather slow so I'm trying to get rid of them first.

I've looked at functions like numpy.repeat and numpy.tile but they don't work since that only runs the function once and then keeps repeating that result of the function. I've also looked at numpy.fromfunction, but I can't seem to get that to work and don't think I can use that. The documentation on numpy.fromfunction says "Construct an array by executing a function over each coordinate". I don't think that's particularly useful since the arguments for the functions stay the same. It's the random element inside the function that creates the difference in each iteration.

If anyone knows how I can solve this that would be very much appreciated, or has a different numpy function I didn't find during my google search that does what I need. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire