TheAlgorithms/Python · error · ZeroDivisionError

df must be > 0

Error message

df must be > 0

What it means

Raised as ZeroDivisionError by inverse_document_frequency when smoothing is False/omitted and the document frequency df is 0. The unsmoothed formula log10(n/df) divides by df, so a term appearing in no documents would divide by zero; the code raises deliberately with a descriptive message.

Source

Thrown at machine_learning/word_frequency_functions.py:117

    Traceback (most recent call last):
     ...
    ValueError: log10(0) is undefined.
    >>> inverse_document_frequency(1, 3)
    0.477
    >>> inverse_document_frequency(0, 3)
    Traceback (most recent call last):
     ...
    ZeroDivisionError: df must be > 0
    >>> inverse_document_frequency(0, 3,True)
    1.477
    """
    if smoothing:
        if n == 0:
            raise ValueError("log10(0) is undefined.")
        return round(1 + log10(n / (1 + df)), 3)

    if df == 0:
        raise ZeroDivisionError("df must be > 0")
    elif n == 0:
        raise ValueError("log10(0) is undefined.")
    return round(log10(n / df), 3)


def tf_idf(tf: int, idf: int) -> float:
    """
    Combine the term frequency
    and inverse document frequency functions to
    calculate the originality of a term. This
    'originality' is calculated by multiplying
    the term frequency and the inverse document
    frequency : tf-idf = TF * IDF
    @params : tf, the term frequency, and idf, the inverse document
    frequency
    @examples :
    >>> tf_idf(2, 0.477)
    0.954

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass smoothing=True so the denominator becomes 1+df (sklearn-style Laplace smoothing).
  2. Filter terms with df == 0 out of the vocabulary before computing IDF.
  3. Rebuild the df table on the same corpus you compute IDF over.

Example fix

# before
idf = inverse_document_frequency(n_docs, df)  # df == 0, no smoothing

# after
idf = inverse_document_frequency(n_docs, df, True)  # smoothed: 1 + log10(n/(1+df))
Defensive patterns

Strategy: validation

Validate before calling

if df > 0:
    idf = inverse_document_frequency(n_docs, df)
else:
    idf = inverse_document_frequency(n_docs, df, True)  # smoothed handles df=0

Prevention

When it happens

Trigger: Calling inverse_document_frequency(n, 0) without the third argument (smoothing defaults falsy). This happens for terms in the vocabulary that occur in zero documents in the current corpus slice.

Common situations: Vocabularies built from a larger corpus then applied to a smaller subset, stop-word filtering that zeroes out some df counts, or new/unseen terms looked up against stale df tables.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/386d3e1bc67dca01. Report an issue: GitHub.