import numpy as np
def readMatrix(filename):
rows = []
for line in open(filename):
columns = []
for number in string.split(line):
columns.append(float(number))
rows.append(columns)
return numpy.array(rows)
def writeMatrix(a, filename):
f = open(filename, 'w')
for row in a:
for number in row:
f.write(str(number) + ' ')
f.write('\n')
f.close()
def TaylorMatrixExp(A):
I = identity(len(A))
return (I + A + (1./2.)*(dot(A,A)) + (1./6.)*(dot(dot(A,A),A)) + (1./24.)*(dot(dot(A,A),dot(A,A))))
A = readMatrix('matrix.txt')
l, v = eig(A)
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = array(exp(l))[i]
VLV = dot(dot(v,L),inv(v))
writeMatrix(VLV,'expA.txt')
ExponentA = TaylorMatrixExp(A)
writeMatrix(ExponentA,'expA.txt')
それが読み取るマトリックスは次のとおりです。
2 2
16 6
readMatrix (テキストファイルから行列を読み取る)、writeMatrix (行列をファイルに書き込む)、および TaylorMatrixExp (配列を取得して展開する) の 2 つの 3 つの関数を定義しました。最初に readMatrix を使用して上記の行列を含むテキスト ファイルを読み取り、それを配列 A に配置します。A の固有値を取得して配列 l に配置し、A の固有ベクトルを配列 v に配置します。最終的に値を配置します単位行列の対角線を横切る配列 l の 次に、writeMatrix 関数を呼び出して指数を 'expA.txt' に書き込み、次に writeMatrix 関数を再度呼び出して行列 ExponentA を 'expA.txt' に書き込みます。ただし、元のマトリックスを置き換えるので、それをしたくありません。
ファイルに書き込みたい
some# some#
some# some#
some#2 some#2
some#2 some#2
代わりに、最初の行列を置き換えます
some#2 some#2
some#2 some#2