Skip to content

Instantly share code, notes, and snippets.

@arcaravaggi
Last active July 21, 2022 13:04
Show Gist options
  • Save arcaravaggi/72b63b6552941f33f7b3955e0600e2fd to your computer and use it in GitHub Desktop.
Save arcaravaggi/72b63b6552941f33f7b3955e0600e2fd to your computer and use it in GitHub Desktop.
Generate a set of autocorrelated random normal variates
##Generates a set of autocorrelated random normal variates
#
#INPUT
# n: number of variates to generate
# mean, sd: mean and standard deviation of the normal distribution
# r: the autocorrelation coefficient (between 0 and 1)
rautonorm <- function(n,mean=0,sd=1,r){
ranfunc <- function(i,z,r) sqrt(1-r^2) * sum(z[2:(i+1)]*r^(i-(1:i))) + z[1]*r^i
z <- rnorm(n)
mean + sd*c(z[1], sapply(1:(n-1), ranfunc, z, r))
}
plot(rautonorm(n = 500, r = 0.75))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment