Conjugate Priors
Overview
Conjugate priors are a central idea in Bayesian inference: they are prior distributions that produce posterior distributions in the same family after observing data. This property turns many updates into closed-form algebra, making Bayesian workflows fast, interpretable, and practical in spreadsheets and production analytics. In applied settings, conjugacy is especially valuable for streaming updates, uncertainty quantification, and credible-interval reporting when full MCMC is unnecessary. The tools in this category focus on common conjugate pairs used in binomial, count-rate, and normal-data models.
The unifying concepts are prior hyperparameters, sufficient statistics, and posterior updating. Instead of reprocessing all raw observations, conjugate models update beliefs through compact summaries such as success counts, sample means, and sample variances. These updates also support direct posterior summaries through quantile functions, which map probability levels to credible bounds. In practice, this enables a clean pipeline: specify a prior, update with data, then extract interpretable posterior moments or interval endpoints.
Implementation is grounded in SciPy and its statistical primitives, especially scipy.special and scipy.stats. SciPy provides numerically stable special functions and distribution quantiles that are critical for robust Bayesian calculations, including extreme tails and large-parameter regimes. The category combines those library calls with explicit conjugate-update formulas so analysts can move between theory and day-to-day decision support.
For Beta-Binomial workflows, BB_LOGBETA, BB_POST_UPDATE, and BB_QBETA cover normalization, posterior updating, and posterior quantiles for Bernoulli/binomial proportions. BB_LOGBETA evaluates \log B(\alpha,\beta) stably, which appears in marginal likelihood and evidence-style calculations. BB_POST_UPDATE applies the canonical updates \alpha' = \alpha + x and \beta' = \beta + n - x, returning posterior parameters and moments. BB_QBETA then converts posterior hyperparameters into percentile-based summaries such as lower and upper credible bounds for conversion rates, defect probabilities, or event risks.
For positive scale and rate uncertainty, GAMMA_POST_Q and INVGAMMA_POST_Q provide quantile extraction from two core conjugate posterior families. GAMMA_POST_Q is used when posterior beliefs are modeled with a Gamma law, common for Poisson or exponential-rate settings where parameters must remain positive. INVGAMMA_POST_Q targets inverse-Gamma posteriors, widely used for variance uncertainty in normal models. Together they let practitioners produce one-sided or two-sided credible limits directly from hyperparameters without numerical integration.
For normal-data models, NIG_POST_UPDATE and NN_POST_UPDATE handle two standard conjugate regimes for the mean (and optionally variance). NN_POST_UPDATE addresses the known-variance case, combining prior precision with data precision to yield posterior mean and variance in closed form. NIG_POST_UPDATE extends to unknown variance via the Normal-Inverse-Gamma family, updating (\mu,\kappa,\alpha,\beta) from sample summaries. These functions are useful in forecasting, measurement calibration, A/B estimation with Gaussian assumptions, and any context requiring transparent posterior updates with minimal computational overhead.
BB_LOGBETA
This function computes the natural logarithm of the Beta function for positive shape parameters. In Bayesian conjugate analysis, log-Beta terms are commonly used to evaluate normalizing constants and marginal likelihood components in a numerically stable way.
For a > 0 and b > 0, the quantity is:
\log B(a,b) = \log\left(\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}\right)
Computing this directly is often unstable for large parameters, so a specialized implementation is preferred.
Excel Usage
=BB_LOGBETA(alpha, beta)
alpha(float, required): First Beta-function shape parameter (positive).beta(float, required): Second Beta-function shape parameter (positive).
Returns (float): Natural logarithm of the Beta function for the supplied parameters.
Example 1: Log-Beta with symmetric shapes
Inputs:
| alpha | beta |
|---|---|
| 3 | 3 |
Excel formula:
=BB_LOGBETA(3, 3)
Expected output:
-3.4012
Example 2: Log-Beta with asymmetric shapes
Inputs:
| alpha | beta |
|---|---|
| 2.5 | 7 |
Excel formula:
=BB_LOGBETA(2.5, 7)
Expected output:
-4.8254
Example 3: Log-Beta for larger parameters
Inputs:
| alpha | beta |
|---|---|
| 40 | 60 |
Excel formula:
=BB_LOGBETA(40, 60)
Expected output:
-67.9686
Example 4: Log-Beta with fractional parameters
Inputs:
| alpha | beta |
|---|---|
| 0.8 | 1.4 |
Excel formula:
=BB_LOGBETA(0.8, 1.4)
Expected output:
-0.0645007
Python Code
Show Code
from scipy.special import betaln as scipy_betaln
def bb_logbeta(alpha, beta):
"""
Compute the log-Beta term used in conjugate posterior calculations.
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.betaln.html
This example function is provided as-is without any representation of accuracy.
Args:
alpha (float): First Beta-function shape parameter (positive).
beta (float): Second Beta-function shape parameter (positive).
Returns:
float: Natural logarithm of the Beta function for the supplied parameters.
"""
try:
alpha = float(alpha)
beta = float(beta)
if alpha <= 0 or beta <= 0:
return "Error: alpha and beta must be positive"
return float(scipy_betaln(alpha, beta))
except Exception as e:
return f"Error: {str(e)}"Online Calculator
BB_POST_UPDATE
This function performs conjugate updating for a Binomial likelihood with a Beta prior. It returns the posterior Beta hyperparameters along with posterior mean and variance for the underlying success probability.
With prior \text{Beta}(\alpha, \beta), observed successes x, and trials n, the posterior is:
\alpha' = \alpha + x, \qquad \beta' = \beta + n - x
The posterior mean and variance are then computed from \alpha' and \beta'.
Excel Usage
=BB_POST_UPDATE(alpha, beta, successes, trials)
alpha(float, required): Prior alpha hyperparameter (positive).beta(float, required): Prior beta hyperparameter (positive).successes(int, required): Observed number of successes (count).trials(int, required): Total number of Bernoulli trials (count).
Returns (list[list]): 2D array containing posterior parameters and posterior moments.
Example 1: Balanced prior with moderate observed data
Inputs:
| alpha | beta | successes | trials |
|---|---|---|---|
| 2 | 2 | 6 | 10 |
Excel formula:
=BB_POST_UPDATE(2, 2, 6, 10)
Expected output:
| Result | |
|---|---|
| 8 | 6 |
| 0.571429 | 0.0163265 |
Example 2: Informative prior with additional successes
Inputs:
| alpha | beta | successes | trials |
|---|---|---|---|
| 10 | 4 | 12 | 20 |
Excel formula:
=BB_POST_UPDATE(10, 4, 12, 20)
Expected output:
| Result | |
|---|---|
| 22 | 12 |
| 0.647059 | 0.00652496 |
Example 3: Sparse data with weak prior
Inputs:
| alpha | beta | successes | trials |
|---|---|---|---|
| 1.2 | 1.8 | 1 | 3 |
Excel formula:
=BB_POST_UPDATE(1.2, 1.8, 1, 3)
Expected output:
| Result | |
|---|---|
| 2.2 | 3.8 |
| 0.366667 | 0.0331746 |
Example 4: Posterior update with zero observed successes
Inputs:
| alpha | beta | successes | trials |
|---|---|---|---|
| 3 | 5 | 0 | 8 |
Excel formula:
=BB_POST_UPDATE(3, 5, 0, 8)
Expected output:
| Result | |
|---|---|
| 3 | 13 |
| 0.1875 | 0.0089614 |
Python Code
Show Code
pass
def bb_post_update(alpha, beta, successes, trials):
"""
Update Beta-Binomial posterior hyperparameters from observed counts.
See: https://en.wikipedia.org/wiki/Beta_distribution#Bayesian_inference
This example function is provided as-is without any representation of accuracy.
Args:
alpha (float): Prior alpha hyperparameter (positive).
beta (float): Prior beta hyperparameter (positive).
successes (int): Observed number of successes (count).
trials (int): Total number of Bernoulli trials (count).
Returns:
list[list]: 2D array containing posterior parameters and posterior moments.
"""
try:
alpha = float(alpha)
beta = float(beta)
successes = int(successes)
trials = int(trials)
if alpha <= 0 or beta <= 0:
return "Error: alpha and beta must be positive"
if trials < 0:
return "Error: trials must be nonnegative"
if successes < 0 or successes > trials:
return "Error: successes must be between 0 and trials"
alpha_post = alpha + successes
beta_post = beta + (trials - successes)
total = alpha_post + beta_post
mean_post = alpha_post / total
var_post = (alpha_post * beta_post) / ((total ** 2) * (total + 1.0))
return [[alpha_post, beta_post], [mean_post, var_post]]
except Exception as e:
return f"Error: {str(e)}"Online Calculator
BB_QBETA
This function returns the quantile of a Beta distribution using posterior hyperparameters from a Beta-Binomial model. It is useful for converting posterior parameters into a percentile-based summary such as a credible bound.
Given posterior parameters \alpha and \beta, and probability level p \in [0,1], it computes x such that:
I_x(\alpha, \beta) = p
where I_x is the regularized incomplete beta function.
Excel Usage
=BB_QBETA(alpha, beta, prob)
alpha(float, required): Posterior alpha hyperparameter (positive).beta(float, required): Posterior beta hyperparameter (positive).prob(float, required): Target cumulative probability level in [0, 1].
Returns (float): Quantile value in [0, 1] for the specified posterior probability level.
Example 1: Median quantile for balanced posterior
Inputs:
| alpha | beta | prob |
|---|---|---|
| 5 | 5 | 0.5 |
Excel formula:
=BB_QBETA(5, 5, 0.5)
Expected output:
0.5
Example 2: Upper credible bound quantile
Inputs:
| alpha | beta | prob |
|---|---|---|
| 12 | 8 | 0.95 |
Excel formula:
=BB_QBETA(12, 8, 0.95)
Expected output:
0.770279
Example 3: Quantile for left-skewed posterior
Inputs:
| alpha | beta | prob |
|---|---|---|
| 2 | 10 | 0.8 |
Excel formula:
=BB_QBETA(2, 10, 0.8)
Expected output:
0.248602
Example 4: Quantile for right-skewed posterior
Inputs:
| alpha | beta | prob |
|---|---|---|
| 10 | 2 | 0.2 |
Excel formula:
=BB_QBETA(10, 2, 0.2)
Expected output:
0.751398
Python Code
Show Code
from scipy.special import betaincinv as scipy_betaincinv
def bb_qbeta(alpha, beta, prob):
"""
Compute a Beta posterior quantile for Beta-Binomial models.
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.betaincinv.html
This example function is provided as-is without any representation of accuracy.
Args:
alpha (float): Posterior alpha hyperparameter (positive).
beta (float): Posterior beta hyperparameter (positive).
prob (float): Target cumulative probability level in [0, 1].
Returns:
float: Quantile value in [0, 1] for the specified posterior probability level.
"""
try:
alpha = float(alpha)
beta = float(beta)
prob = float(prob)
if alpha <= 0 or beta <= 0:
return "Error: alpha and beta must be positive"
if prob < 0 or prob > 1:
return "Error: prob must be between 0 and 1"
return float(scipy_betaincinv(alpha, beta, prob))
except Exception as e:
return f"Error: {str(e)}"Online Calculator
GAMMA_POST_Q
This function returns a quantile from a Gamma posterior distribution parameterized by shape and rate. It is useful for extracting credible bounds for positive-rate parameters in conjugate Bayesian models such as Poisson-Gamma and Exponential-Gamma setups.
With shape \alpha, rate \beta, and probability level p, the quantile q_p satisfies:
P(X \le q_p) = p, \quad X \sim \text{Gamma}(\alpha, \text{rate}=\beta)
In SciPy, this is evaluated with scale \theta = 1/\beta.
Excel Usage
=GAMMA_POST_Q(shape, rate, prob)
shape(float, required): Gamma shape parameter (positive).rate(float, required): Gamma rate parameter (positive, reciprocal of scale).prob(float, required): Target cumulative probability level in [0, 1].
Returns (float): Gamma posterior quantile for the requested probability level.
Example 1: Median for Poisson-rate style posterior
Inputs:
| shape | rate | prob |
|---|---|---|
| 6 | 3 | 0.5 |
Excel formula:
=GAMMA_POST_Q(6, 3, 0.5)
Expected output:
1.89005
Example 2: Upper quantile for concentrated posterior
Inputs:
| shape | rate | prob |
|---|---|---|
| 25 | 10 | 0.95 |
Excel formula:
=GAMMA_POST_Q(25, 10, 0.95)
Expected output:
3.37524
Example 3: Lower quantile for dispersed posterior
Inputs:
| shape | rate | prob |
|---|---|---|
| 2.2 | 1.1 | 0.1 |
Excel formula:
=GAMMA_POST_Q(2.2, 1.1, 0.1)
Expected output:
0.579818
Example 4: Intermediate quantile with fractional shape
Inputs:
| shape | rate | prob |
|---|---|---|
| 3.5 | 2.7 | 0.7 |
Excel formula:
=GAMMA_POST_Q(3.5, 2.7, 0.7)
Expected output:
1.55249
Python Code
Show Code
from scipy.stats import gamma as scipy_gamma
def gamma_post_q(shape, rate, prob):
"""
Compute a Gamma posterior quantile from shape-rate parameters.
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html
This example function is provided as-is without any representation of accuracy.
Args:
shape (float): Gamma shape parameter (positive).
rate (float): Gamma rate parameter (positive, reciprocal of scale).
prob (float): Target cumulative probability level in [0, 1].
Returns:
float: Gamma posterior quantile for the requested probability level.
"""
try:
shape = float(shape)
rate = float(rate)
prob = float(prob)
if shape <= 0 or rate <= 0:
return "Error: shape and rate must be positive"
if prob < 0 or prob > 1:
return "Error: prob must be between 0 and 1"
return float(scipy_gamma.ppf(prob, a=shape, scale=1.0 / rate))
except Exception as e:
return f"Error: {str(e)}"Online Calculator
INVGAMMA_POST_Q
This function returns a quantile from an inverse-Gamma distribution, which commonly appears as a conjugate posterior for variance parameters in normal models.
For shape \alpha, scale \beta, and probability level p, it computes q_p such that:
P(X \le q_p) = p, \quad X \sim \text{InvGamma}(\alpha, \beta)
The result is often used as a posterior credible bound for unknown variance.
Excel Usage
=INVGAMMA_POST_Q(shape, scale, prob)
shape(float, required): Inverse-Gamma shape parameter (positive).scale(float, required): Inverse-Gamma scale parameter (positive).prob(float, required): Target cumulative probability level in [0, 1].
Returns (float): Inverse-Gamma posterior quantile for the requested probability level.
Example 1: Median inverse-Gamma posterior quantile
Inputs:
| shape | scale | prob |
|---|---|---|
| 8 | 12 | 0.5 |
Excel formula:
=INVGAMMA_POST_Q(8, 12, 0.5)
Expected output:
1.56469
Example 2: Lower-tail variance credible bound
Inputs:
| shape | scale | prob |
|---|---|---|
| 5.5 | 7 | 0.1 |
Excel formula:
=INVGAMMA_POST_Q(5.5, 7, 0.1)
Expected output:
0.810419
Example 3: Upper-tail variance credible bound
Inputs:
| shape | scale | prob |
|---|---|---|
| 9 | 15 | 0.95 |
Excel formula:
=INVGAMMA_POST_Q(9, 15, 0.95)
Expected output:
3.19473
Example 4: Quantile with fractional shape parameter
Inputs:
| shape | scale | prob |
|---|---|---|
| 3.4 | 4.2 | 0.75 |
Excel formula:
=INVGAMMA_POST_Q(3.4, 4.2, 0.75)
Expected output:
2.05207
Python Code
Show Code
from scipy.stats import invgamma as scipy_invgamma
def invgamma_post_q(shape, scale, prob):
"""
Compute an inverse-Gamma posterior quantile.
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.invgamma.html
This example function is provided as-is without any representation of accuracy.
Args:
shape (float): Inverse-Gamma shape parameter (positive).
scale (float): Inverse-Gamma scale parameter (positive).
prob (float): Target cumulative probability level in [0, 1].
Returns:
float: Inverse-Gamma posterior quantile for the requested probability level.
"""
try:
shape = float(shape)
scale = float(scale)
prob = float(prob)
if shape <= 0 or scale <= 0:
return "Error: shape and scale must be positive"
if prob < 0 or prob > 1:
return "Error: prob must be between 0 and 1"
return float(scipy_invgamma.ppf(prob, a=shape, scale=scale))
except Exception as e:
return f"Error: {str(e)}"Online Calculator
NIG_POST_UPDATE
This function performs conjugate updating for a Normal likelihood with unknown mean and unknown variance using a Normal-Inverse-Gamma prior. It returns the posterior hyperparameters that define the updated joint prior for mean and variance.
With prior (\mu_0, \kappa_0, \alpha_0, \beta_0) and sample summaries (n, \bar{x}, s^2), the posterior updates are:
\kappa_n = \kappa_0 + n, \quad \mu_n = \frac{\kappa_0\mu_0 + n\bar{x}}{\kappa_n}, \quad \alpha_n = \alpha_0 + \frac{n}{2}
\beta_n = \beta_0 + \frac{1}{2}(n-1)s^2 + \frac{\kappa_0 n (\bar{x}-\mu_0)^2}{2\kappa_n}
Excel Usage
=NIG_POST_UPDATE(mu_prior, kappa_prior, alpha_prior, beta_prior, sample_size, sample_mean, sample_var)
mu_prior(float, required): Prior location hyperparameter for the mean.kappa_prior(float, required): Prior mean-strength hyperparameter (positive).alpha_prior(float, required): Prior inverse-gamma shape hyperparameter (positive).beta_prior(float, required): Prior inverse-gamma scale hyperparameter (positive).sample_size(int, required): Number of observations summarized by sample statistics (nonnegative).sample_mean(float, required): Observed sample mean.sample_var(float, required): Observed sample variance using denominator n-1 (nonnegative).
Returns (list[list]): 2D array containing posterior Normal-Inverse-Gamma hyperparameters.
Example 1: Posterior update from moderate sample summary
Inputs:
| mu_prior | kappa_prior | alpha_prior | beta_prior | sample_size | sample_mean | sample_var |
|---|---|---|---|---|---|---|
| 0 | 2 | 3 | 4 | 12 | 1.5 | 2.4 |
Excel formula:
=NIG_POST_UPDATE(0, 2, 3, 4, 12, 1.5, 2.4)
Expected output:
| Result | |
|---|---|
| 1.28571 | 14 |
| 9 | 19.1286 |
Example 2: Small sample with informative prior
Inputs:
| mu_prior | kappa_prior | alpha_prior | beta_prior | sample_size | sample_mean | sample_var |
|---|---|---|---|---|---|---|
| 5 | 10 | 6 | 8 | 3 | 4.6 | 1.2 |
Excel formula:
=NIG_POST_UPDATE(5, 10, 6, 8, 3, 4.6, 1.2)
Expected output:
| Result | |
|---|---|
| 4.90769 | 13 |
| 7.5 | 9.38462 |
Example 3: Large sample with weak prior information
Inputs:
| mu_prior | kappa_prior | alpha_prior | beta_prior | sample_size | sample_mean | sample_var |
|---|---|---|---|---|---|---|
| -2 | 1 | 2 | 2 | 60 | -1.1 | 0.9 |
Excel formula:
=NIG_POST_UPDATE(-2, 1, 2, 2, 60, -1.1, 0.9)
Expected output:
| Result | |
|---|---|
| -1.11475 | 61 |
| 32 | 28.9484 |
Example 4: Zero sample size preserves prior hyperparameters
Inputs:
| mu_prior | kappa_prior | alpha_prior | beta_prior | sample_size | sample_mean | sample_var |
|---|---|---|---|---|---|---|
| 1 | 3 | 4 | 5 | 0 | 2.5 | 1.8 |
Excel formula:
=NIG_POST_UPDATE(1, 3, 4, 5, 0, 2.5, 1.8)
Expected output:
| Result | |
|---|---|
| 1 | 3 |
| 4 | 5 |
Python Code
Show Code
pass
def nig_post_update(mu_prior, kappa_prior, alpha_prior, beta_prior, sample_size, sample_mean, sample_var):
"""
Update Normal-Inverse-Gamma posterior hyperparameters from sample summaries.
See: https://en.wikipedia.org/wiki/Normal-inverse-gamma_distribution
This example function is provided as-is without any representation of accuracy.
Args:
mu_prior (float): Prior location hyperparameter for the mean.
kappa_prior (float): Prior mean-strength hyperparameter (positive).
alpha_prior (float): Prior inverse-gamma shape hyperparameter (positive).
beta_prior (float): Prior inverse-gamma scale hyperparameter (positive).
sample_size (int): Number of observations summarized by sample statistics (nonnegative).
sample_mean (float): Observed sample mean.
sample_var (float): Observed sample variance using denominator n-1 (nonnegative).
Returns:
list[list]: 2D array containing posterior Normal-Inverse-Gamma hyperparameters.
"""
try:
mu_prior = float(mu_prior)
kappa_prior = float(kappa_prior)
alpha_prior = float(alpha_prior)
beta_prior = float(beta_prior)
sample_size = int(sample_size)
sample_mean = float(sample_mean)
sample_var = float(sample_var)
if kappa_prior <= 0 or alpha_prior <= 0 or beta_prior <= 0:
return "Error: kappa_prior, alpha_prior, and beta_prior must be positive"
if sample_size < 0:
return "Error: sample_size must be nonnegative"
if sample_var < 0:
return "Error: sample_var must be nonnegative"
kappa_post = kappa_prior + sample_size
mu_post = (kappa_prior * mu_prior + sample_size * sample_mean) / kappa_post
alpha_post = alpha_prior + 0.5 * sample_size
scatter_term = 0.5 * max(sample_size - 1, 0) * sample_var
mean_shift_term = 0.5 * (kappa_prior * sample_size / kappa_post) * ((sample_mean - mu_prior) ** 2)
beta_post = beta_prior + scatter_term + mean_shift_term
return [[mu_post, kappa_post], [alpha_post, beta_post]]
except Exception as e:
return f"Error: {str(e)}"Online Calculator
NN_POST_UPDATE
This function performs conjugate updating for a Normal likelihood with known observation variance and a Normal prior on the mean. It returns posterior mean and posterior variance for the unknown mean parameter.
If the prior is \mu \sim \mathcal{N}(\mu_0, \sigma_0^2) and the sample mean is \bar{x} from n observations with known variance \sigma^2, then:
\sigma_n^2 = \left(\frac{1}{\sigma_0^2} + \frac{n}{\sigma^2}\right)^{-1}, \qquad \mu_n = \sigma_n^2\left(\frac{\mu_0}{\sigma_0^2} + \frac{n\bar{x}}{\sigma^2}\right)
Excel Usage
=NN_POST_UPDATE(mu_prior, var_prior, sample_mean, known_var, sample_size)
mu_prior(float, required): Prior mean for the unknown normal mean parameter.var_prior(float, required): Prior variance for the unknown mean parameter (positive).sample_mean(float, required): Observed sample mean.known_var(float, required): Known observation variance (positive).sample_size(int, required): Number of observations used to compute sample mean (nonnegative).
Returns (list[list]): 2D array containing posterior mean/variance and precision summaries.
Example 1: Posterior mean shrinks between prior mean and sample mean
Inputs:
| mu_prior | var_prior | sample_mean | known_var | sample_size |
|---|---|---|---|---|
| 0 | 4 | 1.2 | 1 | 10 |
Excel formula:
=NN_POST_UPDATE(0, 4, 1.2, 1, 10)
Expected output:
| Result | |
|---|---|
| 1.17073 | 0.097561 |
| 10.25 | 10 |
Example 2: Strong prior influence with small sample size
Inputs:
| mu_prior | var_prior | sample_mean | known_var | sample_size |
|---|---|---|---|---|
| 2 | 0.5 | 5 | 4 | 3 |
Excel formula:
=NN_POST_UPDATE(2, 0.5, 5, 4, 3)
Expected output:
| Result | |
|---|---|
| 2.81818 | 0.363636 |
| 2.75 | 0.75 |
Example 3: Weak prior and large sample produce data-dominant posterior
Inputs:
| mu_prior | var_prior | sample_mean | known_var | sample_size |
|---|---|---|---|---|
| -1 | 10 | 0.2 | 2 | 50 |
Excel formula:
=NN_POST_UPDATE(-1, 10, 0.2, 2, 50)
Expected output:
| Result | |
|---|---|
| 0.195219 | 0.0398406 |
| 25.1 | 25 |
Example 4: Zero sample size returns prior-driven posterior
Inputs:
| mu_prior | var_prior | sample_mean | known_var | sample_size |
|---|---|---|---|---|
| 1.5 | 3 | 4 | 2 | 0 |
Excel formula:
=NN_POST_UPDATE(1.5, 3, 4, 2, 0)
Expected output:
| Result | |
|---|---|
| 1.5 | 3 |
| 0.333333 | 0 |
Python Code
Show Code
pass
def nn_post_update(mu_prior, var_prior, sample_mean, known_var, sample_size):
"""
Update Normal posterior parameters for unknown mean with known variance.
See: https://en.wikipedia.org/wiki/Conjugate_prior#Continuous_distributions
This example function is provided as-is without any representation of accuracy.
Args:
mu_prior (float): Prior mean for the unknown normal mean parameter.
var_prior (float): Prior variance for the unknown mean parameter (positive).
sample_mean (float): Observed sample mean.
known_var (float): Known observation variance (positive).
sample_size (int): Number of observations used to compute sample mean (nonnegative).
Returns:
list[list]: 2D array containing posterior mean/variance and precision summaries.
"""
try:
mu_prior = float(mu_prior)
var_prior = float(var_prior)
sample_mean = float(sample_mean)
known_var = float(known_var)
sample_size = int(sample_size)
if var_prior <= 0 or known_var <= 0:
return "Error: var_prior and known_var must be positive"
if sample_size < 0:
return "Error: sample_size must be nonnegative"
prior_precision = 1.0 / var_prior
data_precision = sample_size / known_var
post_precision = prior_precision + data_precision
var_post = 1.0 / post_precision
mu_post = (prior_precision * mu_prior + data_precision * sample_mean) / post_precision
return [[mu_post, var_post], [post_precision, data_precision]]
except Exception as e:
return f"Error: {str(e)}"Online Calculator