python verify Benford's Law

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_33189961/article/details/98338103

Benford's Law

Also known as Benford law , indicating a pile of data derived from real life, the probability of occurrence of 1 as the first digit of the number is about three percent of the total , nearly three times the expected value of intuition come to the 1/9. Promotion, the larger the number, the lower the probability that it led to several numbers appear. It can be used to check whether there is a variety of data fraud .

By the way, with matplotlib.pyplot this library, the following data to the factorial of 1 to 1000, for example, violence verify what:

 code show as below:

import matplotlib.pyplot as plt
import math

def firstDigital(x):
    while x >= 10:
        x //= 10
    return x

if __name__ == "__main__":
    n = 1
    frequency = [0] * 9  #记录第一位数字中1-9数字出现次数
    for i in range(1,1000):
        n *= i
        m = firstDigital(n) - 1
        frequency[m] += 1
    print(frequency)
    plt.plot(frequency,"r-",linewidth=2)
    plt.plot(frequency, "go", markersize=8)
    plt.grid(True)
    plt.show()

Note: the detailed data as follows: [293, 176, 124, 101, 69, 87, 51, 51, 47]

A large number of digital predecessors under test probability distributions :

The first digit Probability
1 0.301
2 0.176
3 0.125
4 0.097
5 0.079
6 0.067
7 0.058
8 0.051
9 0.046

 

 

Guess you like

Origin blog.csdn.net/qq_33189961/article/details/98338103
law