Guest User

Untitled

a guest
Jun 26th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. import math,random
  2. import matplotlib.pyplot as plt
  3.  
  4. # Binary Entropy function
  5. def BinEnt(p):
  6.   if p <= 0.0 or p >= 1.0:
  7.     return 0.0
  8.   return p*math.log2(1.0/p) + (1.0-p)*math.log2(1.0/(1.0-p))
  9.  
  10.  
  11. # https://wiki.python.org/moin/BitManipulation
  12. def ones_and_length(n):
  13.   ones = 0
  14.   length = 0
  15.   while n > 0:
  16.     ones += (n & 1)
  17.     length += 1
  18.     n >>= 1
  19.   return ones, length
  20.  
  21. # return entropy with leading-style length and non-leading
  22. def bit_ents(n, full_length):
  23.   ones, length = ones_and_length(n)
  24.   if ones == 0:
  25.     return 0.0, 0.0
  26.   leading_p = float(ones)/float(length)
  27.   non_p = float(ones)/float(full_length)
  28.   return BinEnt(leading_p), BinEnt(non_p)
  29.  
  30.  
  31. def trial(full_length):
  32.   maximum = (1 << full_length) - 1
  33.   n = random.randint(0, maximum)
  34.   m = random.randint(0, maximum)
  35.   lHn,Hn = bit_ents(n, full_length)
  36.   lHtimes, Htimes = bit_ents(n*m, 2*full_length)
  37.   lHplus, Hplus = bit_ents(n+m, full_length+1)
  38.   return [lHn, lHtimes, lHplus, Hn, Htimes, Hplus]
  39.  
  40.  
  41. def do_trials(full_length, num_trials):
  42.   results = [0.0]*6
  43.   for t in range(num_trials):
  44.     temp = trial(full_length)
  45.     for j in range(len(temp)):
  46.       results[j] += temp[j]
  47.   for j in range(len(results)):
  48.     results[j] /= float(num_trials)
  49.   return results
  50.  
  51.  
  52. num_trials = 10000
  53. lengths = [10, 20, 40, 80, 160, 320, 640, 1280]
  54. #lengths = [5, 10, 20, 40, 80]
  55. res = [do_trials(l, num_trials) for l in lengths]
  56. addone_res = [do_trials(l+1, num_trials) for l in lengths]
  57.  
  58. plt.figure()
  59. plt.plot(lengths, [a[0] for a in res], label="$G(k)$")
  60. plt.plot(lengths, [a[2] for a in res], label="$H_{n+m}$")
  61. plt.plot(lengths, [a[1] for a in res], label="$H_{n\cdot m}$")
  62. plt.title("Bit 'entropy'")
  63. plt.xlabel("k")
  64. plt.ylabel("average entropy")
  65. plt.legend()
  66.  
  67.  
  68. plt.figure()
  69. plt.plot(lengths, [a[0] for a in addone_res], label="$G(k+1)$")
  70. plt.plot(lengths, [a[2] for a in res], label="$H_{n+m}$")
  71. plt.title("Bit 'entropy'")
  72. plt.xlabel("k")
  73. plt.ylabel("average entropy")
  74. plt.legend()
  75.  
  76. plt.figure()
  77. plt.plot(lengths[:-1], [a[0] for a in res][1:], label="$G(2k)$")
  78. plt.plot(lengths[:-1], [a[1] for a in res][:-1], label="$H_{n\cdot m}$")
  79. plt.title("Bit 'entropy'")
  80. plt.xlabel("k")
  81. plt.ylabel("average entropy")
  82. plt.legend()
  83.  
  84.  
  85. plt.show()
Add Comment
Please, Sign In to add comment