2
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.

2
  • 3
    try putting at the top of the 2.7 source file this: from __future__ import division and see how that goes. Commented Nov 28, 2015 at 8:12
  • @Keith, thanks, this works as well. Commented Nov 28, 2015 at 11:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.