⚙

IntroducciónOrigenPor qué ocurreDistribucionesCómo se mideOtros usosBibliografía
IntroductionOriginWhy it happensDistributionsHow it is measuredOther usesBibliography

Imagina una lista de números reales: poblaciones, facturas, longitudes de ríos o votos por provincia. Mira solo su primer dígito. Cabría esperar que cada dígito, del 1 al 9, apareciera en una novena parte de los casos.

Pero no es así: mientras que el 1 aparece cerca del 30 % de las veces, el 9 lo hace en menos del 5 %. Esta regularidad se denomina Ley de Newcomb–Benford.

Sin embargo, no es una regla obligatoria, sino una tendencia: se cumple en muchos casos, pero no en todos. Auditores, estadísticos y periodistas la usan como un primer filtro para encontrar cifras que conviene revisar (Nigrini, 2012), también en elecciones, aunque con cautela (Pericchi y Torres, 2011; Deckert, Myagkov y Ordeshook, 2011; Mebane, 2011).

Origen

En 1881 el astrónomo canadiense-estadounidense Simon Newcomb notó que las primeras páginas de las tablas de logaritmos, libros que antes de las calculadoras servían para convertir productos en sumas, estaban más gastadas que las últimas. Propuso que la probabilidad de que un número empiece por \(d\) es \(\log_{10}(1+1/d)\) (Newcomb, 1881). En 1938 el físico Frank Benford lo comprobó con más de 20 000 números de fuentes muy distintas. Theodore Hill dio la primera explicación estadística general (Hill, 1995) y Mark Nigrini la llevó a la auditoría (Nigrini, 2012). Hoy se aplica también a datos epidemiológicos, científicos y electorales (Berger y Hill, 2015).

Por qué ocurre

Piensa en una cantidad que crece un tanto por ciento fijo cada año, como una población. Para pasar de 100 a 200 tiene que duplicarse; para pasar de 900 a 1000 le basta con crecer un 11 %. Por eso pasa mucho más tiempo empezando por 1 que por 9. Lo mismo ocurre con cualquier número que resulte de multiplicar muchos factores.

Fíjate además en la escala. Si existiera una ley universal sobre los primeros dígitos, debería funcionar igual en euros que en dólares, en metros que en pies. El único reparto de primeras cifras que no cambia al cambiar de unidad es el de Benford.

Para lectores avanzados: si la mantisa \(\{\log_{10} x\}\), es decir, la parte decimal del logaritmo, se distribuye de forma uniforme en \([0,1)\), los dígitos siguen exactamente la Ley de Benford. Hill demostró que la invariancia de escala, y también la de base, implica esa distribución, y que la mezcla de muestras de distribuciones elegidas al azar tiende a Benford (Hill, 1995).

Distribuciones

La probabilidad de que el primer dígito sea \(d\) es

\[P(D_1=d)=\log_{10}\!\left(1+\frac{1}{d}\right),\qquad d=1,\dots,9.\]
\(d\) 1 2 3 4 5 6 7 8 9
\(P\) 30,1 % 17,6 % 12,5 % 9,7 % 7,9 % 6,7 % 5,8 % 5,1 % 4,6 %

El segundo dígito puede ser 0, y su reparto es mucho más plano: va del 12 % para el 0 al 8,5 % para el 9. El tercero y el cuarto son ya casi uniformes. En general, para la posición \(n\),

\[P(D_n=d)=\sum_{k=10^{n-2}}^{10^{n-1}-1}\log_{10}\!\left(1+\frac{1}{10k+d}\right),\qquad n\ge 2.\]
Probabilidad de cada dígito en la primera, segunda, tercera y cuarta posición.

Siendo un poco más imaginativos, podemos tomar los dos primeros dígitos juntos, de 10 a 99: siguen \(P(D_1D_2=m)=\log_{10}(1+1/m)\). Esta prueba es más fina y detecta importes repetidos. El último dígito de un recuento grande, en cambio, no sigue Benford: debería ser uniforme, un 10 % para cada dígito. Quien inventa cifras suele repetir unos dígitos y evitar otros, y eso se nota (Beber y Scacco, 2012).

Estas distribuciones se cumplen bien cuando las cifras abarcan varios órdenes de magnitud (por ejemplo, de 10 a 100 000), no tienen un tope ni un mínimo impuesto y no son números asignados, como teléfonos o códigos postales. No se cumplen con alturas de personas, con precios redondeados a propósito ni con cifras que tienen un máximo: los votos de una mesa electoral, por ejemplo, no pueden superar el número de electores de esa mesa. Por eso una desviación en votos por mesa puede ser completamente normal.

Cómo se mide la desviación

El parámetro estándar para cuantificar la desviación es la MAD (desviación absoluta media): la distancia media entre el porcentaje observado y el que predice Benford, dígito a dígito,

\[\mathrm{MAD}=\frac{1}{K}\sum_{d}\left|\hat p_d-p_d\right|.\]

Nigrini propuso estos umbrales, que también usa el paquete R benford.analysis (Nigrini, 2012; Cinelli, 2014):

✓✓ muy cerca ✓ cerca dudoso ✗ no se ajusta
Primer dígito ≤ 0,006 ≤ 0,012 ≤ 0,015 > 0,015
Segundo dígito ≤ 0,008 ≤ 0,010 ≤ 0,011 > 0,011
Dos primeros ≤ 0,0012 ≤ 0,0018 ≤ 0,0022 > 0,0022

Los umbrales suponen muestras grandes. Con pocas cifras la MAD crece por puro azar. Si se cumpliera Benford, su valor esperado sería \(\mathrm{E}[\mathrm{MAD}]\approx\frac1K\sum_d\sqrt{2p_d(1-p_d)/(\pi n)}\).

La prueba clásica es la de ji cuadrado, \(\chi^2=\sum_d (O_d-np_d)^2/(np_d)\), que compara los recuentos observados \(O_d\) con los esperados \(np_d\). De ella sale el p-valor: la probabilidad de ver al menos una desviación así si los datos siguieran Benford. Como los p-valores son difíciles de interpretar, este sitio muestra por defecto el s-valor, \(S=-\log_2 p\) (Greenland, 2019): un resultado con \(S=10\) es tan sorprendente como sacar 10 caras seguidas al lanzar una moneda. Hasta 4 o 5 caras no es nada raro; varias decenas indican una desviación clara. El botón p / s de la parte superior cambia entre ambos.

Con muchos datos, cualquier diferencia mínima da un s-valor enorme: mira simultáneamente el s-valor (¿es real?) y la MAD (¿es grande?).

La distancia d*, \(d^{*}=\sqrt{\sum_d(\hat p_d-p_d)^2}\,/\,1{,}03631\) para el primer dígito, es la distancia euclídea a Benford normalizada entre 0 y 1 (Wei y Vellwock, 2020); por encima de 0,25 conviene cautela (Goodman, 2016). Cada dígito muestra además un intervalo de confianza de 1σ, 2σ o 3σ (el 68,3 %, 95,4 % o 99,7 % de las muestras si se cumpliera Benford); las barras rojas, «anómalas», quedan fuera. Las cifras sospechosas listan los grupos de dos primeros dígitos que más se apartan, como getSuspects (Cinelli, 2014), y las cifras repetidas muestran si un mismo importe explica un pico.

El estadístico por dígito es \(z_d=\left(|\hat p_d-p_d|-\tfrac{1}{2n}\right)\big/\sqrt{p_d(1-p_d)/n}\), con corrección de continuidad (Nigrini, 2012); el intervalo es \(p_d\pm\left(k\sqrt{p_d(1-p_d)/n}+\tfrac{1}{2n}\right)\) con \(k=1,2,3\). Los dígitos se toman con la precisión del propio conjunto: si casi todas las cifras tienen céntimos, 50,00 cuenta como 5000. Un dígito en la posición \(n\) solo se usa si la cifra tiene al menos \(n\) dígitos. Los ceros se excluyen.

Otros usos

Hasta ahora habíamos hablado únicamente de tablas y cifras numéricas, pero ¿no es acaso una imagen una gran tabla de valores? Una fotografía digital se guarda como una suma de patrones de frecuencia en bloques de 8×8 píxeles (la transformada discreta del coseno, base del formato JPEG). Los primeros dígitos de esos coeficientes siguen una forma generalizada de la Ley de Benford (Fu, Shi y Su, 2007):

\[p(d)=N\log_{10}\!\left(1+\frac{1}{s+d^{\,q}}\right).\]

Una foto recomprimida, retocada o generada por ordenador puede alterar ese patrón. El mapa de la imagen colorea cada zona según lo que se aparta. Un cielo liso o un texto también se apartan, así que es una pista, no una prueba.

Bibliografía

Imagine a list of real numbers: populations, invoices, river lengths or votes per province. Look only at their first digit. One would expect each digit, from 1 to 9, to appear in one ninth of the cases.

But it does not: while 1 appears in about 30% of cases, 9 appears in less than 5%. This regularity is called the Newcomb–Benford Law.

However, it is not a strict rule but a tendency: it holds in many cases, but not in all. Auditors, statisticians and journalists use it as a first filter to find figures worth checking (Nigrini, 2012), also in elections, although with caution (Pericchi and Torres, 2011; Deckert, Myagkov and Ordeshook, 2011; Mebane, 2011).

Origin

In 1881 the Canadian-American astronomer Simon Newcomb noticed that the first pages of logarithm tables, books used before calculators to turn products into sums, were more worn than the last ones. He proposed that the probability of a number starting with \(d\) is \(\log_{10}(1+1/d)\) (Newcomb, 1881). In 1938 the physicist Frank Benford tested it on more than 20,000 numbers from very different sources. Theodore Hill gave the first general statistical explanation (Hill, 1995) and Mark Nigrini brought it to auditing (Nigrini, 2012). Today it is also applied to epidemiological, scientific and electoral data (Berger and Hill, 2015).

Why it happens

Think of a quantity that grows by a fixed percentage each year, like a population. To go from 100 to 200 it must double; to go from 900 to 1000 it only needs to grow by 11%. So it spends much longer starting with 1 than with 9. The same happens with any number that results from multiplying many factors.

Notice also the scale. If there were a universal law about first digits, it should work equally in euros and dollars, in metres and feet. The only spread of first digits that does not change when the unit changes is Benford's.

For advanced readers: if the mantissa \(\{\log_{10} x\}\), the fractional part of the logarithm, is uniformly distributed on \([0,1)\), the digits follow Benford's Law exactly. Hill proved that scale invariance, and also base invariance, implies this distribution, and that mixing samples from randomly chosen distributions tends to Benford (Hill, 1995).

Distributions

The probability that the first digit is \(d\) is

\[P(D_1=d)=\log_{10}\!\left(1+\frac{1}{d}\right),\qquad d=1,\dots,9.\]
\(d\) 1 2 3 4 5 6 7 8 9
\(P\) 30.1% 17.6% 12.5% 9.7% 7.9% 6.7% 5.8% 5.1% 4.6%

The second digit can be 0, and its distribution is much flatter: from 12% for 0 to 8.5% for 9. The third and fourth digits are already almost uniform. In general, for position \(n\),

\[P(D_n=d)=\sum_{k=10^{n-2}}^{10^{n-1}-1}\log_{10}\!\left(1+\frac{1}{10k+d}\right),\qquad n\ge 2.\]
Probability of each digit in the first, second, third and fourth position.

Being a little more imaginative, we can take the first two digits together, from 10 to 99: they follow \(P(D_1D_2=m)=\log_{10}(1+1/m)\). This finer test detects repeated amounts. The last digit of a large count, by contrast, does not follow Benford: it should be uniform, 10% for each digit. People who invent figures tend to repeat some digits and avoid others, and that shows (Beber and Scacco, 2012).

These distributions hold well when the figures span several orders of magnitude (for example, from 10 to 100,000), have no imposed cap or floor, and are not assigned numbers such as phone numbers or postcodes. They do not hold for people's heights, deliberately rounded prices or capped figures: votes at a polling station, for example, cannot exceed the number of voters registered there. So a deviation in votes per station can be perfectly normal.

How the deviation is measured

The standard parameter to quantify the deviation is the MAD (mean absolute deviation): the average distance between the observed share and Benford's, digit by digit,

\[\mathrm{MAD}=\frac{1}{K}\sum_{d}\left|\hat p_d-p_d\right|.\]

Nigrini proposed these thresholds, also used by the R package benford.analysis (Nigrini, 2012; Cinelli, 2014):

✓✓ very close ✓ close doubtful ✗ does not fit
First digit ≤ 0.006 ≤ 0.012 ≤ 0.015 > 0.015
Second digit ≤ 0.008 ≤ 0.010 ≤ 0.011 > 0.011
First two ≤ 0.0012 ≤ 0.0018 ≤ 0.0022 > 0.0022

The thresholds assume large samples. With few figures the MAD grows by chance alone. If Benford held, its expected value would be \(\mathrm{E}[\mathrm{MAD}]\approx\frac1K\sum_d\sqrt{2p_d(1-p_d)/(\pi n)}\).

The classical test is the chi-squared test, \(\chi^2=\sum_d (O_d-np_d)^2/(np_d)\), which compares observed counts \(O_d\) with expected ones \(np_d\). It yields the p-value: the probability of seeing at least a deviation this large if the data followed Benford. As p-values are hard to read, this site shows the s-value by default, \(S=-\log_2 p\) (Greenland, 2019): a result with \(S=10\) is as surprising as tossing 10 heads in a row with a coin. Up to 4 or 5 heads is nothing odd; several tens indicate a clear deviation. The p / s button at the top switches between the two.

With many data, any tiny difference gives a huge s-value: look at the s-value (is it real?) and the MAD (is it large?) together.

The distance d*, \(d^{*}=\sqrt{\sum_d(\hat p_d-p_d)^2}\,/\,1.03631\) for the first digit, is the Euclidean distance to Benford scaled between 0 and 1 (Wei and Vellwock, 2020); values above 0.25 deserve caution (Goodman, 2016). Each digit also shows a confidence interval of 1σ, 2σ or 3σ (68.3%, 95.4% or 99.7% of samples if Benford held); red, "anomalous" bars fall outside. Suspect figures list the first-two-digit groups that deviate most, as getSuspects does (Cinelli, 2014), and repeated figures show whether a single amount explains a spike.

The per-digit statistic is \(z_d=\left(|\hat p_d-p_d|-\tfrac{1}{2n}\right)\big/\sqrt{p_d(1-p_d)/n}\), with continuity correction (Nigrini, 2012); the interval is \(p_d\pm\left(k\sqrt{p_d(1-p_d)/n}+\tfrac{1}{2n}\right)\) with \(k=1,2,3\). Digits are taken at the dataset's own precision: if almost all figures carry cents, 50.00 counts as 5000. A digit at position \(n\) is only used when the figure has at least \(n\) digits. Zeros are excluded.

Other uses

So far we have only talked about tables and numerical figures, but is an image not just a large table of values? A digital photo is stored as a sum of frequency patterns in 8×8 pixel blocks (the discrete cosine transform behind JPEG). The first digits of those coefficients follow a generalised form of Benford's Law (Fu, Shi and Su, 2007):

\[p(d)=N\log_{10}\!\left(1+\frac{1}{s+d^{\,q}}\right).\]

A recompressed, edited or computer-generated photo can change that pattern. The image map colours each area by how far it departs. Flat sky or text also departs, so it is a clue, not proof.

Bibliography

    MIT · CC BY 4.0