Skip to content

Truncated normal distribution

3 messages · Ravi Longia, ravirrrr, Ben Bolker

1 day later
#
I have the following code, where we need to solve for mu and sigma, when we
have mut and sdt. Can you suggest how to use a solve function in R to do
that? I am new to R and am not sure how to go from defining the functions,
to solving for them. 

Thanks


truncated <- function(x)
{

mu=x[1];
sigma=x[2];


f <- function(x) (1/(sigma*sqrt(2*pi)))*exp(-(x-mu)^2/(2*sigma^2));

pdf.fun <- function(x) x*f(x);

sd.fun <- function(x) (x)^2*f(x);

st=integrate(sd.fun,lower=-Inf,upper=1)$value;

a=integrate(pdf.fun,lower=-Inf,upper=1)$value;

a1=integrate(f,lower=-Inf,upper=1)$value;

mut <- a/a1;
sdt <- sqrt((st/a1)-(a/a1)^2);

}
#
ravirrrr wrote:
truncated <- function(x)
{
  mu <- x[1]
  sigma <- x[2]
  pdf.fun <- function(x) x*dnorm(x,mu,sigma)
  sd.fun <- function(x) x^2*dnorm(x,mu,sigma)
  st <- integrate(sd.fun,lower=-Inf,upper=1)$value;
  a <- integrate(pdf.fun,lower=-Inf,upper=1)$value;
  a1 <- pnorm(1,mu,sigma)
  mut <- a/a1;
  sdt <- sqrt((st/a1)-(a/a1)^2)
  c(mut,sdt)
}

truncated(c(0,1))  ## sensible: mean <0, sd<1
truncated(c(0,0.1)) ## sensible: approx 0,1
## trouble for small values 
truncated(c(0,0.001))
truncated(c(0,0.0001))

optfun <- function(p,target=c(0,1)) {
  sum((truncated(p)-target)^2)
}

target <- c(mu=-0.5,sd=2)
fit1 <- optim(fn=optfun,
      par=c(-0.5,2),
      target=target)
fit1

truncated(fit1$par) ## didn't succeed

## let's do something easier -- can we
## work backward to a known value?

t1 <- truncated(c(0,1))

optim(fn=optfun,
      par=c(0,1),
      target=t1)
          

optim(fn=optfun,
      par=c(0.5,2),
      target=t1)