随机数生成函数作为python中的参数



我想传递一个生成随机正常数字的函数给另一个函数,做一些计算并再次传递随机函数x次。最后应该有一个包含x列的数据框,其中包含不同的随机生成的结果。

我的代码是这样的:

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)

但是这总是给我相同的列。

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

我认为你不能这样传递函数。你应该分别传递函数和参数

之类的
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)

注意cov矩阵应该是对称的,并且是正的。

问题是您的np.random.rand(...)语句在调用函数之前已经被评估了。如果每次调用函数都需要新的随机数,则需要在函数中调用np.random.rand(...)

最新更新