【发布时间】:2016-03-02 08:16:03
【问题描述】:
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()
在 python 3.5 中运行此代码给出正确答案[9.999999999858039, -2.9999999999432156]
但在 python 2.7 中给出答案[7,-2]。为什么?
这是利用矩阵求解方程组的高斯-赛德尔方法的实现。
【问题讨论】:
-
尝试在 2.7 源文件的顶部放置:
from __future__ import division看看结果如何。 -
@Keith,谢谢,这也可以。
标签: python-2.7 python-3.x