'random number generating function as argument in python

I want to pass a function which generates random normal numbers to another function, do some calculations and pass again the random function x times. At the end there should be a Dataframe with x colums with diffrent randomly generated outcomes.

My code looks like this:

timeframe = 10
nr_simulations = 10
mean_vec = np.random.rand(10)
cov_mat = np.random.rand(10,10)
r_n = np.zeros((timeframe, nr_simulations))

def test_function(func, timeframe, nr_simulations):
    for i in range(0, nr_simulations):
        r_n[:,i] = func.mean(axis=1)


def simulate_normal_numbers(mean_vec, cov_mat, timeframe):
    return np.random.multivariate_normal(mean_vec, cov_mat, timeframe)

But this gives me always identical columns.

test_function(simulate_normal_numbers(mean_vec, cov_mat, timeframe), timeframe, nr_simulations)


Solution 1:[1]

I don't think you can pass the function like that. You should pass the function and the argument separately

Something like

import numpy as np
timeframe = 10
nr_simulations = 10
mean_vec = np.random.rand(10)

cov_mat =  np.random.rand(10,10)
cov_mat = np.maximum( cov_mat, cov_mat.transpose() )
r_n = np.zeros((timeframe, nr_simulations))

def test_function(func, timeframe, nr_simulations, arg):
    for i in range(0, nr_simulations):
        r_n[:,i] = func(*arg).mean(axis=1)



def simulate_normal_numbers(mean_vec, cov_mat, timeframe):
    return np.random.multivariate_normal(mean_vec, cov_mat, timeframe)

test_function(simulate_normal_numbers , timeframe, nr_simulations,arg = (mean_vec, cov_mat, timeframe))
print(r_n)

be aware that the cov matrix should be symmetrical and positive.

Solution 2:[2]

The problem is that your np.random.rand(...) statements are already being evaluated before the function is called. If you want new random numbers every time the function is called, you will need to call np.random.rand(...) inside your function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ymmx
Solution 2 Elias Mi