Skip to content

Instantly share code, notes, and snippets.

@rkiyanchuk
Created April 20, 2017 21:50
Show Gist options
  • Save rkiyanchuk/53acb78d9d5e316b278b6ab6a1423a5d to your computer and use it in GitHub Desktop.
Save rkiyanchuk/53acb78d9d5e316b278b6ab6a1423a5d to your computer and use it in GitHub Desktop.
Benford's law in Fibonacci sequence
"""Verify that Fibonacci sequence follows Benford's law."""
from pprint import pprint
def fibonacci(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def lead_num_freq(nums):
freqs = dict(zip(range(1, 10), [0]*9))
for i in nums:
lead = str(i)[0]
freqs[int(lead)] += 1
for digit in freqs:
freqs[digit] = freqs[digit] / len(nums) * 100
return freqs
def main():
fibs = [fibonacci(i) for i in range(1, 10000)]
pprint(lead_num_freq(fibs), width=1)
if __name__ == "__main__":
main()
@rkiyanchuk
Copy link
Author

rkiyanchuk commented Apr 20, 2017

Benford's law

$ python fib_benford_law.py 
{1: 30.11301130113011,
 2: 17.621762176217622,
 3: 12.49124912491249,
 4: 9.68096809680968,
 5: 7.920792079207921,
 6: 6.68066806680668,
 7: 5.8005800580058,
 8: 5.1305130513051305,
 9: 4.56045604560456}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment