close

hw3.py

# -*- coding: utf-8 -*-
from datetime import date
import time
import random
import operator
import os
import sys
from numpy import *

dmatrix = []
dvector = []
try :
    print "go\n"
    fmatrix = file("matrix.txt", 'r')
    print "has matrix.txt\n"
    fvector = file("vector.txt", 'r')
    print "has vector.txt\n"
    col = 0;
    for line in fmatrix:
        col += 1
        for num in line:
            if str(num).isdigit():
                dmatrix.append(float(num))
    for line in fvector:
        for num in line:
            if str(num).isdigit():
                dvector.append(float(num))
    fmatrix.close()
    fvector.close()

    dmatrix = array(dmatrix)
    dmatrix.shape = (col, dmatrix.size/col)
    dvector = array(dvector)
    dvector.shape = (dvector.size)
    print "vector:\n", dvector
    print "matrix:\n", dmatrix
    invmatrix = linalg.inv(dmatrix)
    print "invmatrix:\n", invmatrix
    ans = dvector.dot(invmatrix)
    print "ans = vector dot invmatrix :\n", ans
except :
    print "Fail read data\n"
    pass

raw_input()

matrix.txt
2 3
1 2
vector.txt
1 1

結果:

go

has matrix.txt

has vector.txt

vector:
[ 1.  1.]
matrix:
[[ 2.  3.]
 [ 1.  2.]]
invmatrix:
[[ 2. -3.]
 [-1.  2.]]
ans = vector dot invmatrix :
[ 1. -1.]


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 讓地獄深紅的天亮 的頭像
    讓地獄深紅的天亮

    !壞人必需做好事!

    讓地獄深紅的天亮 發表在 痞客邦 留言(0) 人氣()