bitfreqs.html
001| """Bit Frequencies Chart."""
002|
003| from sys import argv
004| from os import path
005| import matplotlib.pyplot as plt
006| from matplotlib.ticker import MultipleLocator, FormatStrFormatter
007| from n256 import int_2_base
008|
009| BasePath = r'C:\CJS\prj\Python\blog\proj'
010| ImgsPath = path.join(BasePath,'img')
011| Filename = 'bitfreqs.png'
012|
013|
014| ymin,ymax = 0, 100
015| nbits = 100
016|
017|
018| def get_nck_data (nb=16):
019| def n_choose_k (n, k):
020| def fact (n):
021| def f (n):
022| return 1 if n==0 else n*f(n-1)
023| return f(n)
024| return 0 if n<k else int(fact(n)/(fact(k)*fact(n-k)))
025| return [n_choose_k(nb,k) for k in range(nb+1)]
026|
027|
028| def get_histogram_data (nb=8):
029| hist = {}
030| for n in range(pow(2,nb)):
031| bits = int_2_base(n, base=2, raw=True)
032| ones = sum(bits)
033| if ones not in hist: hist[ones] = 0
034| hist[ones] += 1
035| return hist
036|
037|
038| def make_chart (xs, ys):
039| fig, ax = plt.subplots()
040| fig.suptitle('Number of Occurances of One Bits')
041| fig.set_figwidth(4.40)
042| fig.set_figheight(3.20)
043| fig.subplots_adjust(left=0.15, right=0.98, bottom=0.16, top=0.92)
044|
045| ax.set_xlabel('Number of set bits')
046| ax.set_xlim(0, nbits)
047| ax.xaxis.set_major_locator(MultipleLocator(20))
048| ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
049|
050| ax.set_ylabel('Number of Occurances')
051| ax.set_ylim(ymin, ymax)
052| ax.yaxis.set_major_locator(MultipleLocator(50))
053| ax.yaxis.set_minor_locator(MultipleLocator(10))
054| ax.yaxis.set_major_formatter(FormatStrFormatter('%de27'))
055|
056| ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
057| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
058| ax.tick_params(which='major', axis='both', direction='out', color='#000000')
059| ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
060|
061| ax.bar(xs,ys, width=1.00, color='#008000', alpha=1.0, zorder=10)
062|
063| fn = path.join(ImgsPath, Filename)
064| fig.savefig(fn)
065| print('wrote: %s' % fn)
066| print()
067|
068|
069| def main ():
070| xs = range(nbits+1)
071|
072|
073|
074| ys = [n//pow(10,27) for n in get_nck_data(nb=nbits)]
075|
076| for t in zip(xs,ys):
077| print(t)
078| print()
079|
080| make_chart(xs, ys)
081|
082|
083| if __name__ == '__main__':
084| print(argv[0])
085| print()
086| main()
087| print()
088|
089| '''eof'''
090|