BARTLETT

Overview

The BARTLETT function performs Bartlett’s test to evaluate whether multiple groups have the same variance, which is a core assumption in many parametric analyses. It quantifies evidence against the null hypothesis of equal population variances and reports both a test statistic and p-value. This makes it useful as a homogeneity-of-variance check before procedures such as one-way ANOVA.

For k groups with sample sizes n_i, sample variances s_i^2, and total size N=\sum_{i=1}^{k} n_i, Bartlett’s statistic is:

T = \frac{(N-k)\ln(s_p^2) - \sum_{i=1}^{k}(n_i-1)\ln(s_i^2)}{C},

where the pooled variance is

s_p^2 = \frac{\sum_{i=1}^{k}(n_i-1)s_i^2}{N-k},

and the correction factor is

C = 1 + \frac{1}{3(k-1)}\left(\sum_{i=1}^{k}\frac{1}{n_i-1} - \frac{1}{N-k}\right).

Under the null hypothesis, T is approximately distributed as \chi^2_{k-1}, which is used to compute the p-value.

This implementation wraps scipy.stats.bartlett from SciPy. In this tool, input is provided as a 2D list where each row is treated as one sample group, and the output is returned as [[statistic, p_value]]. Bartlett’s test is sensitive to departures from normality, so robust alternatives are often preferred when data are strongly non-normal.

In practice, the function is commonly used in experimental design, biostatistics, manufacturing quality analysis, and A/B-style group comparisons where variance consistency matters. It helps analysts decide whether equal-variance assumptions are reasonable before selecting downstream inferential tests. Used alongside distribution diagnostics, it supports more reliable model and test selection.

This example function is provided as-is without any representation of accuracy.

Excel Usage

=BARTLETT(sample)
  • sample (list[list], required): 2D list of numeric values. Rows are interpreted as sample groups.

Returns (list[list]): 2D list [[statistic, p_value]], or error message string.

Example 1: Equal variances

Inputs:

sample
10 20 30
10 20 30
10 20 30

Excel formula:

=BARTLETT({10,20,30;10,20,30;10,20,30})

Expected output:

Result
0 1
Example 2: Distinct variances

Inputs:

sample
1 2 3
1 5 9

Excel formula:

=BARTLETT({1,2,3;1,5,9})

Expected output:

Result
2.41207 0.120403
Example 3: Three groups with different spreads

Inputs:

sample
3 4 5 6
3 8 13 18
2 2.5 3 3.5

Excel formula:

=BARTLETT({3,4,5,6;3,8,13,18;2,2.5,3,3.5})

Expected output:

Result
12.2142 0.00222697
Example 4: Two groups with moderate variance difference

Inputs:

sample
4 5 6 7
4 6 8 10

Excel formula:

=BARTLETT({4,5,6,7;4,6,8,10})

Expected output:

Result
1.1476 0.284053

Python Code

Show Code
import numpy as np
from scipy.stats import bartlett as scipy_bartlett

def bartlett(sample):
    """
    Performs Bartlett's test for equal variances across multiple samples.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bartlett.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        sample (list[list]): 2D list of numeric values. Rows are interpreted as sample groups.

    Returns:
        list[list]: 2D list [[statistic, p_value]], or error message string.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        sample = to2d(sample)

        # Validate input type and shape
        if not isinstance(sample, list) or len(sample) < 2:
             return "Error: Invalid input: sample must be a 2D list with at least two rows."
        if any(not isinstance(row, list) or len(row) < 2 for row in sample):
             return "Error: Invalid input: each sample group must be a list with at least two elements."

        # Logic from func_bartlett.py
        # Check if each row is a sample group (default behavior if numeric)
        if len(sample) > 0 and len(sample[0]) > 0 and all(isinstance(x, (int, float)) for x in sample[0]):
             groups = sample
        else:
             # Try to transpose (e.g. if passed as list of columns? Or handles non-numeric?)
             # In YAML/Excel context, input is usually values.
             # This else block might be unreachable if input is verified numeric traversing
             # but let's keep it.
             # Actually, zip(*sample) transposes.
             groups = [list(col) for col in zip(*sample)]

        # Ensure at least two groups
        if len(groups) < 2:
            return "Error: Invalid input: sample must contain at least two groups."

        # Ensure each group has at least two elements
        if any(len(group) < 2 for group in groups):
            return "Error: Invalid input: each sample group must have at least two elements."

        # Flatten and check for invalid values (and ensure float)
        groups_float = []
        for group in groups:
            new_group = []
            for val in group:
                try:
                    fval = float(val)
                    new_group.append(fval)
                except (ValueError, TypeError):
                    return "Error: Invalid input: all values must be numeric."
            groups_float.append(new_group)

        stat, pvalue = scipy_bartlett(*groups_float)

        stat = float(stat)
        pvalue = float(pvalue)

        if np.isnan(stat) or np.isnan(pvalue):
            return "Error: Result is NaN."

        return [[stat, pvalue]]

    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

2D list of numeric values. Rows are interpreted as sample groups.