DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Async Context Manager Mocking in Python Tests
  • Supercharging Pytest: Integration With External Tools
  • Exploring the Purpose of Pytest Fixtures: A Practical Guide
  • Automating Python Multi-Version Testing With Tox, Nox and CI/CD

Trending

  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Teradata Performance and Skew Prevention Tips
  1. DZone
  2. Data Engineering
  3. Data
  4. Using a Chi-Square Test to Satisfy Benford's Law With Python

Using a Chi-Square Test to Satisfy Benford's Law With Python

Learn how to run a chi-square test in Python to analyze the distribution of factorials to satisfy Benford's Law, which is often used in fraud detection.

By 
John Cook user avatar
John Cook
·
Jun. 23, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
7.5K Views

Join the DZone community and get the full member experience.

Join For Free

here's a fun quick excursion using a very short python program that illuminates the somewhat counterintuitive basis for benford's law. quick, interesting and refreshing. we're all geeks here right?

a while back i wrote about how the leading digits of factorials follow benford’s law . that is, if you look at just the first digit of a sequence of factorials, they are not evenly distributed. instead, 1’s are most popular, then 2’s, etc. specifically, the proportion of factorials starting with n is roughly log 10 (1 + 1/ n ).

someone has proved that the limiting distribution of leading digits of factorials exactly satisfies benford’s law . but if we didn’t know this, we might use a chi-square statistic to measure how well the empirical results match expectations. as i argued in the previous post , statistical tests don’t apply here, but they can be useful anyway in giving us a way to measure the size of the deviations from theory.

benford’s law makes a better illustration of the chi-square test than the example of prime remainders because the bins are unevenly sized, which they’re allowed to be in general. in the prime remainder post, they were all the same size.

the original post on leading digits of factorial explains why we compute the leading digits the way we do. only one detail has changed: the original post used python 2 and this one uses python 3. integer division was the default in python 2, but now in python 3 we have to use // to explicitly ask for integer division, floating point division being the new default.

here’s a plot of the distribution of the leading digits for the first 500 factorials.

and here’s code to compute the chi-square statistic:


    from math import factorial, log10

    def leading_digit_int(n):
        while n > 9:
            n = n//10
        return n

    def chisq_stat(o, e):
        return sum( [(o - e)**2/e for (o, e) in zip(o, e)] )

    # waste the 0th slot to make the code simpler.
    digits = [0]*10

    n = 500
    for i in range(n):
        digits[ leading_digit_int( factorial(i) ) ] += 1

    expected = [ n*log10(1 + 1/n) for n in range(1, 10) ]

    print( chisq_stat(digits[1:], expected) )

this gives a chi-square statistic of 7.693, very near the mean value of 8 for a chi-square distribution with eight degrees of freedom. (there are eight degrees of freedom, not nine, because if we know how many factorials start with the digits 1 through 8, we know how many start with 9.)

so the chi-square statistic suggests that the deviation from benford’s law is just what we’d expect from random data following benford’s law. and as we said before, this suggestion turns out to be correct.

Law (stochastic processes) Python (language) philosophy Testing Statistics

Published at DZone with permission of John Cook, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Async Context Manager Mocking in Python Tests
  • Supercharging Pytest: Integration With External Tools
  • Exploring the Purpose of Pytest Fixtures: A Practical Guide
  • Automating Python Multi-Version Testing With Tox, Nox and CI/CD

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: