coding corelated random variables in Python

Viewed 34

I am trying to code two random variables with a correlation. I have been given $Z_1\tilde N(0,1)$ and $Z_2\tilde N(0,1)$. I is also given $cor(Z_1,Z_2)=\rho$. So I need the formula to get $Z_2$ from $Z_1$. Initially, I was trying this code:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
rho=0.5
N=100
Z1=np.random(N)
Z2=np.random(N)
return Z2

However, then I realized that $Z_2$ is now no longer correlated to $Z_1$. So I want to ask how I can get the correct $Z_2$.

1 Answers

Let $\alpha$ such that $\alpha^2+\rho^2 = 1$. Let $X, Y$ be independent $N(0,1)$ distributed variables. Set $Z_1 := \rho * X + \alpha * Y$ and $Z_2:=X$. Now $Z1, Z_2$ should fulfill your requirements.

Related