首页 > 代码库 > 本福特定律

本福特定律

本福特定律

技术分享

测试结果

技术分享
比例
1 : 30.0766922307
2 : 17.639213071
3 : 12.504168056
4 : 9.66988996332
5 : 7.9693231077
6 : 6.60220073358
7 : 5.80193397799
8 : 5.16838946315
9 : 4.56818939647
附代码
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Apr 03 23:31:14 2017
  4. @author: LoveDMR
  5. 本福特定律实验 Benford
  6. """
  7. import matplotlib.pyplot as plt
  8. def first_num( n ):
  9. while( n / 10 > 0 ):
  10. n = n / 10
  11. return n
  12. def second_num( n ):
  13. while( n / 100 > 0 ):
  14. n = n / 10
  15. return n%10
  16. if __name__ == ‘__main__‘:
  17. fib_first = [ 0 ] * 10
  18. fib_second = [ 0 ] * 10
  19. fac_first = [ 0 ] * 10
  20. fac_second = [ 0 ] * 10
  21. a , b = 1,1
  22. k = 1
  23. for i in range(1,3000):
  24. # 斐波那契数列
  25. a , b = b , a + b
  26. first_fib = first_num( a )
  27. second_fib = second_num( a )
  28. fib_first[first_fib] = fib_first[first_fib] + 1
  29. fib_second[second_fib] = fib_second[second_fib] + 1
  30. # 阶乘
  31. k *= i
  32. first_fac = first_num( k )
  33. second_fac = second_num( k )
  34. fac_first[first_fac] = fac_first[first_fac] + 1
  35. fac_second[second_fac] = fac_second[second_fac] + 1
  36. for n , i in enumerate(fib_first[1:],1):
  37. print n , ":" , i * 100.0 / sum(fib_first[1:])
  38. plt.figure( figsize =( 16, 8 ) )
  39. plt.subplot(121)
  40. plt.plot( range(1,10) , fib_first[1:] , ‘r-‘ , label=‘Fib‘)
  41. plt.plot( range(1,10) , fac_first[1:] , ‘b-‘ ,label=‘Fac‘)
  42. plt.title(‘First Num‘)
  43. plt.legend()
  44. plt.grid()
  45. plt.subplot(122)
  46. plt.plot( range(0,10) , fib_second , ‘r-‘ , label=‘Fib‘)
  47. plt.plot( range(0,10) , fac_second , ‘b-‘ , label=‘Fac‘)
  48. plt.title(‘Second Num‘)
  49. plt.legend()
  50. plt.grid()
  51. plt.show()

本福特定律