简体   繁体   中英

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM