[英]Simulation from a customised distribution in R
您可以尝试使用Markov链蒙特卡罗方法,例如Metropolis-Hastings算法。 https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm
这不行吗?
special <- function(x) {
if (x <= -1) {
val <- dnorm(x) / (1+exp(-x-1))
} else if ((x > -1) & (x < 1)) {
val <- dnorm(x) / 2
} else {
val <- dnorm(x) / (1+exp(-x+1))
}
return(val)
}
special(-2)
[1] 0.01452041
special(-0.5)
[1] 0.1760327
您可以使用sample
执行此操作...
#define some x values
x <- seq(-5, 5, 0.001)
#define the pdf as above
f <- function(x) {
if (x <= -1) {
y <- dnorm(x)/(1+exp(-x-1))
} else if (x >= 1) {
y <- dnorm(x)/(1+exp(-x+1))
} else {
y <- dnorm(x)/2
}
return(y)
}
#calculate values of pdf for all x
fx <- f(x)
#create sample using these probabilities
samp <- sample(x, size=10000, replace=TRUE, prob=fx)
hist(samp, breaks=50)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.