Reputation: 171
a=[[2,5],[1,3]]
b=[5,1]
r=len(a)
x=[1,1]
def func():
tol=.00000000001;l=0;ite=10000
fnd=0
while(l<ite and fnd==0):
j=0
while(j<r):
temp=b[j]
k=0
while(k<r):
if (j!=k):
temp=temp-a[j][k]*x[k]
k=k+1
c=temp/a[j][j]
if (abs(x[j]-c)<=tol):
fnd=1
break
x[j]=c
j=j+1
l=l+1
if l==ite:
print ("Iterations are over")
print(x)
func()
running this code in python 3.5 gives correct answer [9.999999999858039, -2.9999999999432156]
but gives answer [7,-2]
in python 2.7. Why?
This is implementation of Gauss-Seidel method to find solution of system of equations using matrix.
Upvotes: 2
Views: 162
Reputation: 312219
The difference is in the way python 2 and python 3 handle the /
operator in the line c=temp/a[j][j]
. In python 2, /
performs integer division, while in python 3 it performs floating point division.
Converting temp
to a float
before the division (i..e, c=float(temp)/a[j][j]
) will ensure you get the right answer in both versions.
Upvotes: 3