Last active
July 21, 2022 13:04
-
-
Save arcaravaggi/72b63b6552941f33f7b3955e0600e2fd to your computer and use it in GitHub Desktop.
Generate a set of autocorrelated random normal variates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##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