穴埋め
def abs (x)
if x >=0
x
else
-x
end
end
#a[i][k]の絶対値が最大となるi>=kを探す
def maxrow(a,k)
max_i=k
for i in (k+1)..(a.length()-1)
if abs(a[max_i][k]) < abs(a[i][k])
max_i=i # 穴埋め
end
end
max_i
end
def swap(a,i,j)
tmp=a[i]
a[i]=a[j]
a[j]=tmp
end
def gjp(a) # Gauss-Jordan method WITH pivoting
row = a.length()
col = a[0].length()
for k in 0..(col-2)
max=maxrow(a,k) # find absolute-maximal coeff.
swap(a,k,max) # swap rows
akk = a[k][k]
for i in 0..(col-1) # normalize row k
a[k][i]=a[k][i]*1.0/akk
end
for i in 0..(row-1) # eliminate column k
if i != k # of all rows but k
aik = a[i][k]
for j in k..(col-1)
a[i][j] = a[i][j] - aik * a[k][j]
end
end
end
end
a
end
実行例
b=[[1,-50,-3,-90],
[-85,2,-25,-6],
[79,5,30,-1]]
gjp(b) -> [[1.0, 0.0, 0.0, 1.0], [-0.0, 1.0, 0.0, 2.0], [0.0, 0.0, 1.0, -3.0]]
b=[[1,-50,-3,-90],
[-85,2,-25,-6],
[79,5,30,-1]]
gj(b) -> [[1.0, 0.0, 0.0, 0.999999999999977], [-0.0, 1.0, 0.0, 2.0], [0.0, 0.0, 1.0, -2.99999999999996]]
gjp(b), gj(b)はいずれも引数として与えた配列(この例では b)を書き換えてしまうので,実行するたびにbを定義し直す必要がある.
gjp([[1,-50,-3,-90],[-85,2,-25,-6],[79,5,30,-1]])
gj([[1,-50,-3,-90],[-85,2,-25,-6],[79,5,30,-1]])
のようにして与えるのもOK