Reputation: 29
I have got these code, But it gives a zero division error. I am not able to figure out what is wrong. I need your help. Thank you. :)
from math import sqrt
def inisialisasi():
filename = raw_input('File will be read? ')
return filename
def readdatafile(filename):
datafile = open('kalibration.txt','r')
datax = []; datay = []; datae = []; i = 0
for row in datafile:
i +=1
data = row.split()
x = float(data[0])
datax.append(x)
y = float(data[1])
datay.append(y)
e = float(data[2])
datae.append(e)
print 'x = %5.2f y = %5.2f e = %5.2f' % (x, y, e)
datafile.close()
n = i
print 'Jumlah data = ', n
return n, datax, datay, datae
def regresilinear(x, y, e):
sum1=0.0; sum2=0.0; sum3=0.0; sum4=0.0; sum5=0.0
for i in range(0, n):
sum1=sum1+(x[i]**2/e[i]**2)
sum2=sum2+(y[i]/e[i]**2)
sum3=sum3+(x[i]/e[i]**2)
sum4=sum4+(x[i]*y[i])/e[i]**2
sum5=sum5+1/e[i]**2
det = (sum5*sum1)-sum3**2
#parameter a dan b
a = ((sum1*sum2)-(sum3*sum4))/det
b = ((sum5*sum4)-(sum3)*(sum2))/det
#ralat
sigmaa2 = sum1/det
sigmab2 = sum5/det
sigmaa = sqrt(sigmaa2)
sigmab = sqrt(sigmab2)
return a, b, sigmaa, sigmab
filename = inisialisasi()
n, datax, datay, datae = readdatafile(filename)
a, b, sigmaa, sigmab = regresilinear(datax,datay, datae)
print 'a= %8.6f b= %8.6f sigmaa= %8.6f sigmab= %8.6f' % (a, b, sigmaa, sigmab)
error :
Traceback (most recent call last):
File "coba6.py", line 55, in
a, b, sigmaa, sigmab = regresilinear(datax, datay, datae)
File "coba6.py", line 42, in regresilinear
a = ((sum1*sum2)-(sum3*sum4))/det
ZeroDivisionError: float division by zero
Upvotes: 2
Views: 13061
Reputation: 3956
Somehow, det
is set equal to 0
. Since you never explicitly prevent that from happening, a single input line like...
1.0 <whatever> 1.0
...can result in division by zero. (The y
value doesn't matter in this case.) After substituting, you'll have:
sum1 = 0.0 + 1.0**2 / 1.0**2 # sum1 == 1.0
sum3 = 0.0 + 1.0 / 1.0**2 # sum3 == 1.0
sum5 = 0.0 + 1 / 1.0**2 # sum5 == 1.0
det = 1.0 * 1.0 - 1.0**2 # det == 0.0
...
a = <whatever> / det # KABOOM!
Actually, no input will also produce this error, since the for
loop in regresilinear
will never alter the various sum*
variables from their default 0.0
values.
If you're sure your input isn't doing this, you might want to add print
statements inside regresilinear
to see how det
is getting set to zero. (Or use the pdb
debugger, if you're familiar with it.)
PS: It would be much easier to debug your functions if they weren't dependent on global data like n
. You don't even need it, since it should always equal the length of the three lists datax
, datay
, and datae
.
PPS: readdatafile
completely ignores its filename
parameter. So if the hard-coded kalibration.txt
file happens to be present but empty, you'll get the exact same ZeroDivisionError
.
Upvotes: 2
Reputation: 19
What does your variable e
look like? That is, what does it contain? If there's values of zero in it, you have your answer.
Upvotes: 0