- 论坛徽章:
- 0
|
编了个小代码,用高斯消元的方法把一个行列式变成上三角的,代码如下:- def dyh_gauss_elimination(list1):
- # This function is used to transform a determination to upper-triangle determination
- temp = list1
- if dyh_query_dimensionality(temp)!=2:
- print 'This is not a determination'
- return False
- loop = min([len(temp),len(temp[0])])
- tolerance = 0.001
- for i in range(1,loop):
- # check the first dimension
- if abs(temp[i-1][i-1]) < tolerance:
- for j in range(i,len(temp)):
- if abs(temp[j][i-1]) > tolerance:
- temp1 = temp[i-1]
- temp[i-1] = temp[j]
- temp[j] = temp1
- break
- if abs(temp[i-1][i-1]) >= tolerance:
- for j in range(i,len(temp)):
- lambda1 = -1.0 * temp[j][i-1]/temp[i-1][i-1]
- for k in range(i-1,len(temp[j])):
- temp[j][k] += lambda1 * temp[i-1][k]
-
- return temp
复制代码 测试情况如下:- >>> from dyh_models import dyh_gauss_elimination as dyh
- >>> b = [[4,-2,1],[-2,4,-2],[1,-2,4]]
- >>> dyh(b)
- [[4, -2, 1], [0.0, 3.0, -1.5], [0.0, 0.0, 3.0]]
- >>> b = [[1]*3]*3
- >>> b
- [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
- >>> dyh(b)
- Traceback (most recent call last):
- File "<stdin>", line 1, in ?
- File "H:\ABAQUS\dyh_models\dyh_models.py", line 228, in dyh_gauss_elimination
- lambda1 = -1.0 * temp[j][i-1]/temp[i-1][i-1]
- ZeroDivisionError: float division
- >>> sys.version
- '2.4.3 (#0, Apr 2 2009, 18:40:00) [MSC v.1400 32 bit (Intel)]'
复制代码 我明明加了if来避免0除情况,怎么没起作用?求高手指点 |
|