Shinylive Apps for Statistical Computation
    • All Apps

    • Inverse CDF Method for Generating Random Numbers
    • Newton-Raphson for the Cauchy Location Likelihood
    • Safeguarded Newton-Raphson for Logistic Regression
    • Gradient-Based Methods for Minimizing Test Functions
    • Gradient-Based Methods for Fitting a Gaussian Neural Network
    • Gradient-Based Methods for Fitting a Poisson Neural Network
    • Nelder–Mead Method for Derivative-Free Minimization
    • EM Algorithm for a Normal Mixture
    • EM Algorithm for a Bivariate Normal Mixture
    • Conjugate Updating for Bayesian Posteriors
    • Quadrature and Laplace Approximation for the Marginal Likelihood of a Normal Mean
    • Midpoint, Laplace and Laplace-Adapted Midpoint Rules for the Marginal Likelihood of Normal Data
    • Rejection Sampling with a Laplace Envelope for the Normal Distribution
    • Rejection Sampling with a Cauchy Envelope for the Gamma Distribution
    • Adaptive Rejection Sampling for the Truncated Normal Distribution
    • Adaptive Rejection Sampling on log X for the Truncated Gamma Distribution
    • Importance Sampling for a Bimodal Distribution (Failure Example)
    • Importance Sampling with a Normal Proposal for Student-t Probabilities
    • Gibbs Sampling for the Cauchy Model with Unknown Location and Scale
    • MCMC Simulators by Chi Feng (external)

Importance Sampling with a Normal Proposal for Student-t Probabilities

Author

Longhai Li

Published

November 27, 2026

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 790
library(shiny)

### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
                       env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    shiny::renderImage({
        info <- shiny::getCurrentOutputInfo()
        w  <- if (is.numeric(width))  width  else info$width()
        h  <- if (is.numeric(height)) height else info$height()
        shiny::req(w > 0, h > 0)
        pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
        if (is.null(pr)) pr <- 1
        f   <- tempfile(fileext = ".png")
        dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
        on.exit(grDevices::dev.off(dev), add = TRUE)
        grDevices::dev.control(displaylist = "enable")
        v <- withVisible(func())
        if (v$visible) print(v$value)
        list(src = f, contentType = "image/png", width = w, height = h,
             coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
    }, deleteFile = TRUE)
}
library(ars)

## rtnorm_ars() and is_t_interval(): identical to the versions defined
## earlier in the chapter (a {shinylive-r} chunk cannot see objects
## defined elsewhere in the document, so they are pasted in verbatim).
rtnorm_ars <- function(n, mu = 0, sigma = 1, lo = 0, hi = Inf) {
    logf   <- function(x) dnorm(x, mu, sigma, log = TRUE)
    fprima <- function(x) -(x - mu) / sigma^2
    if (is.finite(hi)) {
        x0 <- lo + (hi - lo) * c(0.1, 0.5, 0.9)
    } else {
        right <- max(mu, lo) + 3 * sigma
        x0 <- sort(unique(c(lo + 0.1 * sigma, max(lo + 0.2 * sigma, mu + 1e-6), right)))
    }
    ars(n, f = logf, fprima = fprima, x = x0,
        lb = TRUE, xlb = lo, ub = is.finite(hi), xub = if (is.finite(hi)) hi else 0)
}

is_t_interval <- function(S, df, c1, c2, mu, sigma, seed = NULL) {
    if (!is.null(seed)) set.seed(seed)
    X <- rtnorm_ars(S, mu, sigma, c1, c2)

    lZ   <- log(pnorm(c2, mu, sigma) - pnorm(c1, mu, sigma))
    logw <- dt(X, df, log = TRUE) - (dnorm(X, mu, sigma, log = TRUE) - lZ)

    m    <- max(logw)
    v    <- exp(logw - m)
    Chat <- mean(v) * exp(m)
    se   <- sd(v) / sqrt(S) * exp(m)
    wn   <- v / mean(v)                  # normalized weights, mean 1

    list(X = X, wn = wn, Chat = Chat, se = se, ess = S / mean(wn^2),
         truth = pt(c2, df) - pt(c1, df))
}

ui <- fluidPage(
    wellPanel(
        fluidRow(
            column(3, sliderInput("df", HTML("target df &nu;"), min = 1, max = 30, value = 3, step = 1)),
            column(3, sliderInput("c", HTML("interval (c<sub>1</sub>, c<sub>2</sub>)"), min = -5, max = 15,
                                  value = c(1, 3), step = 0.25),
                      checkboxInput("c2inf", HTML("c<sub>2</sub> = &infin;  (infinite-variance case)"), FALSE)),
            column(3, sliderInput("mu", HTML("proposal &mu;"), min = -5, max = 20, value = 0, step = 0.25)),
            column(3, sliderInput("sg", HTML("proposal &sigma;"), min = 0.25, max = 10, value = 1, step = 0.25))),
        fluidRow(
            column(3, selectInput("S", "sample size  S",
                                  choices = c(200, 1000, 5000, 20000), selected = 1000)),
            column(3, br(), actionButton("new", "New sample")),
            column(3, br(), checkboxInput("logw", "log scale for weights", FALSE)))
    ),
    fluidRow(
        column(8, plotOutput("panels", height = "560px")),
        column(4,
            tags$style("#tab td, #tab th { white-space: nowrap; }"),
            h5("Estimate"),
            tableOutput("tab"))
    )
)

server <- function(input, output, session) {

    sim <- reactive({
        S  <- as.integer(input$S)
        c1 <- input$c[1]
        c2 <- if (input$c2inf) Inf else input$c[2]
        validate(need(c2 > c1, "c2 must be greater than c1"))
        mu <- input$mu; sg <- input$sg; df <- input$df

        r <- is_t_interval(S, df, c1, c2, mu, sg, seed = input$new + 1)
        c(r, list(S = S, c1 = c1, c2 = c2, mu = mu, sg = sg, df = df))
    })

    output$panels <- renderPlot({
        s  <- sim()
        c1 <- s$c1; c2 <- s$c2; X <- s$X
        lo <- c1
        hi <- if (is.finite(c2)) c2 else max(max(X) + 0.5, c1 + 5)
        xs <- seq(lo, hi, length.out = 800)

        ## both densities normalized on (c1, c2)
        ft <- dt(xs, s$df) / s$truth
        gt <- dnorm(xs, s$mu, s$sg) / (pnorm(c2, s$mu, s$sg) - pnorm(c1, s$mu, s$sg))
        yl <- c(0, max(ft, gt) * 1.1)

        lwr <- s$Chat - 1.96 * s$se
        upr <- s$Chat + 1.96 * s$se
        covered <- lwr <= s$truth && s$truth <= upr
        ci_col  <- if (covered) "darkgreen" else "firebrick"

        layout(matrix(1:2, 2), heights = c(3, 2))

        ## ---- top panel: the two densities ----------------------------
        par(mar = c(0.4, 5, 3, 1))
        plot(xs, ft, type = "n", ylim = yl, xlim = c(lo, hi),
             xaxt = "n", xlab = "", ylab = "density",
             main = "target and proposal, both normalized on (c1, c2)")
        if (!is.finite(c2)) {
            rect(max(X), yl[1], hi, yl[2],
                 col = adjustcolor("grey60", 0.18), border = NA)
            text(max(X), yl[2], "  no draw ever reached here", adj = c(0, 1.4),
                 col = "grey35", cex = 0.95)
        }
        lines(xs, ft, lwd = 4, col = "firebrick")
        lines(xs, gt, lwd = 3, col = "steelblue")
        rug(X, col = adjustcolor("steelblue", 0.25))
        legend("right", inset = c(0.02, 0), bty = "n", cex = 1.05,
               lwd = c(4, 3), col = c("firebrick", "steelblue"),
               legend = c(
                   sprintf("target: t(df=%g) on (c1, c2)", s$df),
                   sprintf("proposal: N(%.2f, %.2f^2) on (c1, c2)", s$mu, s$sg)))

        ## ---- bottom panel: normalized weights ------------------------
        par(mar = c(4.5, 5, 0.4, 1))
        wn <- s$wn
        if (input$logw) {
            wl <- c(max(min(wn[wn > 0]), 1e-12), max(wn))
            plot(X, wn, type = "n", log = "y", ylim = wl, xlim = c(lo, hi),
                 xlab = "x", ylab = "normalized weight, mean 1 (log scale)")
            segments(X, wl[1], X, wn, col = adjustcolor("grey50", 0.6))
        } else {
            plot(X, wn, type = "n", ylim = c(0, max(wn) * 1.08),
                 xlim = c(lo, hi), xlab = "x", ylab = "normalized weight, mean 1")
            segments(X, 0, X, wn, col = adjustcolor("grey50", 0.6))
        }
        abline(h = 1, lty = 2, col = "darkgreen", lwd = 2)
        legend("topright", inset = c(0.02, 0.05), bty = "n", cex = 1.05,
               lty = 2, lwd = 2, col = "darkgreen", legend = "1  (perfectly balanced weights)")
    })

    output$tab <- renderTable({
        s <- sim()
        lwr <- s$Chat - 1.96 * s$se; upr <- s$Chat + 1.96 * s$se
        data.frame(
            Quantity = c("true P(c1 < X < c2)", "estimate", "95% CI", "CI covers the truth?",
                         "ESS", "ESS (% of S)", "largest weight (% of total)"),
            Value = c(sprintf("%.5g", s$truth), sprintf("%.5g", s$Chat),
                      sprintf("(%.5g, %.5g)", lwr, upr),
                      if (lwr <= s$truth && s$truth <= upr) "yes" else "no",
                      sprintf("%.1f", s$ess), sprintf("%.2f", 100 * s$ess / s$S),
                      sprintf("%.1f", 100 * max(s$wn) / s$S)))
    }, striped = TRUE, align = "ll", width = "100%")
}

shinyApp(ui, server)

About the app

Shows how the choice of constants and proposal determines whether importance sampling of a Student-\(t\) interval is reliable, by displaying the target, the proposal, and the importance weights. A two-handled slider sets \((c_{1},c_{2})\) (or \(c_{2}=\infty\) via the checkbox), and further sliders set the target’s degrees of freedom \(\nu\) and the proposal’s \(\mu,\sigma\); the controls are in the panel at the top, the top plot compares the (normalized) target and proposal densities, the bottom plot shows the normalized importance weights at the sampled points, and the table to the right of the plots gives the true probability, the estimate, its 95% CI (with whether it covers the truth), the effective sample size and the largest weight.

The target and the proposal. The aim is the probability that a Student-\(t\) variable falls in an interval, \[P=P(c_1<X<c_2)=\int_{c_1}^{c_2}t_\nu(x)\,dx=F_\nu(c_2)-F_\nu(c_1),\qquad X\sim t_\nu,\] which is known exactly (the “true” value in the table) and is estimated here by importance sampling with a normal sample. The two densities are both defined on \((c_1,c_2)\).

  • Target: the Student-\(t\) density truncated to the interval, \[f(x)=\frac{t_\nu(x)}{P}\,\mathbf 1\{c_1<x<c_2\},\] whose unnormalized form \(t_\nu(x)\mathbf 1\{c_1<x<c_2\}\) has normalizing constant \(P\), the probability we want.
  • Proposal: yes, the proposal is a truncated normal, a \(N(\mu,\sigma^2)\) density restricted to the same interval, \[g(x)=\frac{\varphi\big((x-\mu)/\sigma\big)/\sigma}{\Phi\big((c_2-\mu)/\sigma\big)-\Phi\big((c_1-\mu)/\sigma\big)}\,\mathbf 1\{c_1<x<c_2\},\] with \(\mu\) and \(\sigma\) set by the sliders (\(\varphi\) and \(\Phi\) are the standard normal density and CDF). The draws \(X_1,\ldots,X_S\sim g\) are generated by adaptive rejection sampling from the truncated normal, so every draw lies inside \((c_1,c_2)\). The top plot shows both normalized densities \(f\) and \(g\) on that interval.

The importance weights and the estimator are \[w_s=\frac{t_\nu(X_s)}{g(X_s)},\qquad \hat P=\frac1S\sum_{s=1}^Sw_s,\qquad E_g(w)=\int_{c_1}^{c_2}t_\nu(x)\,dx=P,\] (the weights of the normalized target \(f\) would differ from these only by the constant factor \(P\)). The standard error is \(s_w/\sqrt S\), with \(s_w\) the sample standard deviation of the weights, which gives the 95% interval. The variance of the weights is finite when the interval is bounded, because then \(w\) is bounded on \((c_1,c_2)\) or at worst a ratio of continuous functions on a compact set. With \(c_2=\infty\) the proposal has normal tails, which decay like \(e^{-x^2/(2\sigma^2)}\), while the \(t_\nu\) tail decays only polynomially, so \(E_g(w^2)=\int t_\nu^2/g\,dx\) diverges: the weights have infinite variance, which is the case the checkbox shows.

The app above puts \(c_{1}\), \(c_{2}\), \(\mu\), \(\sigma\) and the target’s degrees of freedom \(\nu\) under slider control (a checkbox sends \(c_{2}\) to \(\infty\)), and displays, on a common \(x\)-axis: the two truncated densities with a rug of the draws, and the normalized importance weights \(\hat w^\star_{i}=w_{i}\big/\tfrac1S\sum_{j}w_{j}\) (mean 1) at the sampled points. The table beside the plots reports the true \(P(c_{1}<X<c_{2})\), the estimate, its nominal 95% interval and whether the interval covers the truth, the effective sample size and the largest weight. Leave \(c_{2}\) finite and the estimator behaves; check the box and watch it misbehave exactly as the variance calculation predicts, while \(S_{\text{eff}}\) in the table need not warn you either way.

Several settings repay attention.

  • \(c_{2}\) finite (the default). Target and proposal share the same bounded support, so the weights have finite variance: raising \(S\) improves the estimate at the usual \(1/\sqrt S\) rate, and the 95% interval covers about as often as it claims to.
  • Check “\(c_{2}=\infty\)”. This reproduces the divergent case derived above. Raising \(S\) no longer shrinks a variance that does not exist, and repeated New sample draws swing far more than the reported standard error admits. With large \(\nu\) the run-away region is rarely reached, so the app can still look fine by chance; with small \(\nu\) (Cauchy, \(\nu=1\)) it bites often — but \(S_{\text{eff}}\) need not warn you either way.
  • Small \(\sigma\), or \(\mu\) far outside \((c_{1},c_{2})\). Draws pile up wherever the proposal happens to put mass inside the interval, the weights are nearly equal, \(S_{\text{eff}}\) stays high, and the estimate can still miss badly: uniform weights certify only that the proposal is internally consistent, not that it matches the target’s shape there.
  • Large \(\sigma\). One draw’s weight can dominate the sum, \(S_{\text{eff}}\) collapses toward \(1\) — visibly unreliable, which is an improvement on being invisibly unreliable.
NoteR source for this app
library(shiny)

### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
                       env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    shiny::renderImage({
        info <- shiny::getCurrentOutputInfo()
        w  <- if (is.numeric(width))  width  else info$width()
        h  <- if (is.numeric(height)) height else info$height()
        shiny::req(w > 0, h > 0)
        pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
        if (is.null(pr)) pr <- 1
        f   <- tempfile(fileext = ".png")
        dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
        on.exit(grDevices::dev.off(dev), add = TRUE)
        grDevices::dev.control(displaylist = "enable")
        v <- withVisible(func())
        if (v$visible) print(v$value)
        list(src = f, contentType = "image/png", width = w, height = h,
             coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
    }, deleteFile = TRUE)
}
library(ars)

## rtnorm_ars() and is_t_interval(): identical to the versions defined
## earlier in the chapter (a {shinylive-r} chunk cannot see objects
## defined elsewhere in the document, so they are pasted in verbatim).
rtnorm_ars <- function(n, mu = 0, sigma = 1, lo = 0, hi = Inf) {
    logf   <- function(x) dnorm(x, mu, sigma, log = TRUE)
    fprima <- function(x) -(x - mu) / sigma^2
    if (is.finite(hi)) {
        x0 <- lo + (hi - lo) * c(0.1, 0.5, 0.9)
    } else {
        right <- max(mu, lo) + 3 * sigma
        x0 <- sort(unique(c(lo + 0.1 * sigma, max(lo + 0.2 * sigma, mu + 1e-6), right)))
    }
    ars(n, f = logf, fprima = fprima, x = x0,
        lb = TRUE, xlb = lo, ub = is.finite(hi), xub = if (is.finite(hi)) hi else 0)
}

is_t_interval <- function(S, df, c1, c2, mu, sigma, seed = NULL) {
    if (!is.null(seed)) set.seed(seed)
    X <- rtnorm_ars(S, mu, sigma, c1, c2)

    lZ   <- log(pnorm(c2, mu, sigma) - pnorm(c1, mu, sigma))
    logw <- dt(X, df, log = TRUE) - (dnorm(X, mu, sigma, log = TRUE) - lZ)

    m    <- max(logw)
    v    <- exp(logw - m)
    Chat <- mean(v) * exp(m)
    se   <- sd(v) / sqrt(S) * exp(m)
    wn   <- v / mean(v)                  # normalized weights, mean 1

    list(X = X, wn = wn, Chat = Chat, se = se, ess = S / mean(wn^2),
         truth = pt(c2, df) - pt(c1, df))
}

ui <- fluidPage(
    wellPanel(
        fluidRow(
            column(3, sliderInput("df", HTML("target df &nu;"), min = 1, max = 30, value = 3, step = 1)),
            column(3, sliderInput("c", HTML("interval (c<sub>1</sub>, c<sub>2</sub>)"), min = -5, max = 15,
                                  value = c(1, 3), step = 0.25),
                      checkboxInput("c2inf", HTML("c<sub>2</sub> = &infin;  (infinite-variance case)"), FALSE)),
            column(3, sliderInput("mu", HTML("proposal &mu;"), min = -5, max = 20, value = 0, step = 0.25)),
            column(3, sliderInput("sg", HTML("proposal &sigma;"), min = 0.25, max = 10, value = 1, step = 0.25))),
        fluidRow(
            column(3, selectInput("S", "sample size  S",
                                  choices = c(200, 1000, 5000, 20000), selected = 1000)),
            column(3, br(), actionButton("new", "New sample")),
            column(3, br(), checkboxInput("logw", "log scale for weights", FALSE)))
    ),
    fluidRow(
        column(8, plotOutput("panels", height = "560px")),
        column(4,
            tags$style("#tab td, #tab th { white-space: nowrap; }"),
            h5("Estimate"),
            tableOutput("tab"))
    )
)

server <- function(input, output, session) {

    sim <- reactive({
        S  <- as.integer(input$S)
        c1 <- input$c[1]
        c2 <- if (input$c2inf) Inf else input$c[2]
        validate(need(c2 > c1, "c2 must be greater than c1"))
        mu <- input$mu; sg <- input$sg; df <- input$df

        r <- is_t_interval(S, df, c1, c2, mu, sg, seed = input$new + 1)
        c(r, list(S = S, c1 = c1, c2 = c2, mu = mu, sg = sg, df = df))
    })

    output$panels <- renderPlot({
        s  <- sim()
        c1 <- s$c1; c2 <- s$c2; X <- s$X
        lo <- c1
        hi <- if (is.finite(c2)) c2 else max(max(X) + 0.5, c1 + 5)
        xs <- seq(lo, hi, length.out = 800)

        ## both densities normalized on (c1, c2)
        ft <- dt(xs, s$df) / s$truth
        gt <- dnorm(xs, s$mu, s$sg) / (pnorm(c2, s$mu, s$sg) - pnorm(c1, s$mu, s$sg))
        yl <- c(0, max(ft, gt) * 1.1)

        lwr <- s$Chat - 1.96 * s$se
        upr <- s$Chat + 1.96 * s$se
        covered <- lwr <= s$truth && s$truth <= upr
        ci_col  <- if (covered) "darkgreen" else "firebrick"

        layout(matrix(1:2, 2), heights = c(3, 2))

        ## ---- top panel: the two densities ----------------------------
        par(mar = c(0.4, 5, 3, 1))
        plot(xs, ft, type = "n", ylim = yl, xlim = c(lo, hi),
             xaxt = "n", xlab = "", ylab = "density",
             main = "target and proposal, both normalized on (c1, c2)")
        if (!is.finite(c2)) {
            rect(max(X), yl[1], hi, yl[2],
                 col = adjustcolor("grey60", 0.18), border = NA)
            text(max(X), yl[2], "  no draw ever reached here", adj = c(0, 1.4),
                 col = "grey35", cex = 0.95)
        }
        lines(xs, ft, lwd = 4, col = "firebrick")
        lines(xs, gt, lwd = 3, col = "steelblue")
        rug(X, col = adjustcolor("steelblue", 0.25))
        legend("right", inset = c(0.02, 0), bty = "n", cex = 1.05,
               lwd = c(4, 3), col = c("firebrick", "steelblue"),
               legend = c(
                   sprintf("target: t(df=%g) on (c1, c2)", s$df),
                   sprintf("proposal: N(%.2f, %.2f^2) on (c1, c2)", s$mu, s$sg)))

        ## ---- bottom panel: normalized weights ------------------------
        par(mar = c(4.5, 5, 0.4, 1))
        wn <- s$wn
        if (input$logw) {
            wl <- c(max(min(wn[wn > 0]), 1e-12), max(wn))
            plot(X, wn, type = "n", log = "y", ylim = wl, xlim = c(lo, hi),
                 xlab = "x", ylab = "normalized weight, mean 1 (log scale)")
            segments(X, wl[1], X, wn, col = adjustcolor("grey50", 0.6))
        } else {
            plot(X, wn, type = "n", ylim = c(0, max(wn) * 1.08),
                 xlim = c(lo, hi), xlab = "x", ylab = "normalized weight, mean 1")
            segments(X, 0, X, wn, col = adjustcolor("grey50", 0.6))
        }
        abline(h = 1, lty = 2, col = "darkgreen", lwd = 2)
        legend("topright", inset = c(0.02, 0.05), bty = "n", cex = 1.05,
               lty = 2, lwd = 2, col = "darkgreen", legend = "1  (perfectly balanced weights)")
    })

    output$tab <- renderTable({
        s <- sim()
        lwr <- s$Chat - 1.96 * s$se; upr <- s$Chat + 1.96 * s$se
        data.frame(
            Quantity = c("true P(c1 < X < c2)", "estimate", "95% CI", "CI covers the truth?",
                         "ESS", "ESS (% of S)", "largest weight (% of total)"),
            Value = c(sprintf("%.5g", s$truth), sprintf("%.5g", s$Chat),
                      sprintf("(%.5g, %.5g)", lwr, upr),
                      if (lwr <= s$truth && s$truth <= upr) "yes" else "no",
                      sprintf("%.1f", s$ess), sprintf("%.2f", 100 * s$ess / s$S),
                      sprintf("%.1f", 100 * max(s$wn) / s$S)))
    }, striped = TRUE, align = "ll", width = "100%")
}

shinyApp(ui, server)

This app accompanies Importance Sampling in the book.