Skip to content

Numerical precision of normal_lcdf #1284

Description

@alecksphillips

Description

The normal_lcdf(x | mu, sigma) function suffers from precision problems at x >> mu/sigma when compared to the equivalent pnorm(x, mu, sigma, log.p=T) in base R.

Example

R code:

library(rstan)

stan_model_code <- "
functions {
  real test_normal_lcdf(real x) {
    return normal_lcdf(x | 0, 1);
  }
}
parameters{}
model{}"

expose_stan_functions(stanc(model_code = stan_model_code))

x <- seq(7.5,7.51,0.00001)
y_stan <- sapply(x, test_normal_lcdf)
y_R <- pnorm(x,log.p=T)

df <- data.frame(
  x = c(x,x),
  y = c(y_R, y_stan),
  method = factor(c(rep_len("R", length(x)), rep_len("Stan", length(x))))
)

plot(df$x, df$y, col = df$method, xlab = "x", ylab = "normal_lcdf(x)")
legend(x = 7.502, y = -3e-14, legend = levels(df$method), col = c(1:2), pch = 16)

Expected Output:

See plot comparing Stan and R's output here: https://discourse.mc-stan.org/t/numerical-precision-of-normal-lcdf/9685

Current Version:

v2.19.1

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions