TheAlgorithms/Python · error · ValueError
log10(0) is undefined.
Error message
log10(0) is undefined.
What it means
Raised by inverse_document_frequency in word_frequency_functions.py when smoothing=True and the total number of documents n is 0. With smoothing the formula is 1 + log10(n/(1+df)), and log10(0) is mathematically undefined, so the function refuses rather than returning -inf.
Source
Thrown at machine_learning/word_frequency_functions.py:113
smoothing, if True return the idf-smooth
@returns : log10(N/df) or 1+log10(N/1+df)
@examples :
>>> inverse_document_frequency(3, 0)
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 documentView on GitHub (pinned to f5988cc097)
Solutions
- Ensure the corpus is non-empty before computing IDF: check n > 0 at the call site.
- Load/index documents before running the TF-IDF pipeline.
- If an empty corpus is legitimate in your flow, skip IDF computation for those terms rather than calling the function.
Example fix
# before idf = inverse_document_frequency(n_docs, df, True) # n_docs == 0 # after idf = inverse_document_frequency(n_docs, df, True) if n_docs > 0 else None
Defensive patterns
Strategy: validation
Validate before calling
if n_docs > 0:
idf = inverse_document_frequency(n_docs, df, True)
else:
idf = None # empty corpus: no IDF defined Prevention
- Check corpus size before running TF-IDF stages.
- Skip empty shards/batches in distributed document processing.
When it happens
Trigger: Calling inverse_document_frequency(0, df, True) - i.e. n=0 with the smoothing flag set. Note df=0 with smoothing is fine because the denominator becomes 1+df.
Common situations: Computing IDF over an empty corpus during unit tests, before documents are loaded, or when a filtering step removes all documents from a shard.
Related errors
- df must be > 0
- Expected a_coeffs to have {self.order + 1} elements for {sel
- Expected b_coeffs to have {self.order + 1} elements for {sel
- k must not be negative
- n must not be negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/c59c94a2d7f30b2a.
Report an issue: GitHub.