Home > front end >  Generating a random sample where variance of i'th component is 1/i
Generating a random sample where variance of i'th component is 1/i

Time:10-19

I need to write a function that generates a sample of n independent Gaussian variables in dimension d, with expectation of zero and where the variance of the i'th component is 1/i for i=1,...d. The function should return the sample as a matrix of shape (n,d).

I've thought of using rng.standard_normal() but I don't know how to generate a sample so that every i'th component would have a variance 1/i. Any help is appreciated.

CodePudding user response:

Here you go:

import numpy as np
n = 4
d = 3
tmp = [(np.random.multivariate_normal(mean=np.zeros((n,)), cov=np.eye(n) * np.sqrt(1/(d 1)))) for i in range(d)]
res = np.squeeze(np.array(tmp)).T

CodePudding user response:

Using the random package, you can get a list of normal draws with decreasing variance as follows:

import random 
d=4
n=10
l = [random.gauss(0, (1/i)**2) for i in range(1, 1 d)]

You can get a matrix with n rows (bi-dimensional list) using another list comprehension:

mat = [[random.gauss(0, (1/i)**2) for i in range(1, 1 d)] for _ in range(n)]

In other words, if you look at the x value from each line, they would come from the same distribution. In case you need stationarity by row, you could transpose the bi-list you created using list(zip(mat)), or you could change the iteration logic:

mat2 = [[random.gauss(0, (1/i)**2) for _ in range(d)] for i in range(1, 1 n)]

In this instance, every list (line) will have the expected variance and, for list long enough, you can verify this:

import statistics as s
[s.variance(l) for l in mat2]
  • Related