Vote count:
0
I have created a function in Python that computes the histogram of data. It has parameter bins that specifies no. of division.
I have given my code below:
import numpy as np
def histogram_using_numpy(filename, bins=10):
datas = np.loadtxt(filename, delimiter=" ", usecols=(0,))
hist,bin_edges = np.histogram(datas, bins)
return hist
print "from numpy %s" % histogram_using_numpy("ex.txt", bins=10)
def histogram_using_list(filename, bins=10, take_col=0):
f = open(filename,"r")
data = []
for item in f.readlines():
data.append(float(item.split()[take_col]))
f.close()
mi,ma = min(data), max(data)
bin_length = (ma-mi)/bins
def get_count(lis,low,diff):
count = 0
for item in lis:
if item >= low and item < low + diff:
count += 1
return count
tot = []
for i in np.arange(mi, ma, bin_length):
tot.append(get_count(data,i, bin_length))
return tot
print "From my function %s " % histogram_using_list("ex.txt", bins=10)
Now for bins = 10 for both function. the result is:
from numpy [10 19 20 28 15 16 14 11 5 12]
From my function [10, 19, 20, 28, 16, 15, 14, 11, 5, 12]
which is correct. but for bins = 15 I get:
from numpy [ 7 4 18 19 5 24 8 10 13 6 13 6 5 1 11]
From my function [7, 4, 18, 19, 10, 19, 8, 10, 13, 10, 9, 6, 5, 1, 11]
which is incorrect. Is there anything wrong in my code?
asked 52 secs ago
Aucun commentaire:
Enregistrer un commentaire