Python 如何解决稀疏矩阵运算
用Python求解微分线性方程
因为之前用matlab也编写过,所以前不久试着用python写,感觉之间互通点也蛮多的,易理解。
题目:稀疏线性方程组的求解方法
简单的方程如: AX=b
其中
python有很多功能库,这些库对于编程很有帮助,可以在pycharm的Project Interpreter导入库,例如numpy、os、scipy等比较基础的库,
下面是用来求解的代码:
import numpy as np from scipy import linalg import os #输入矩阵维数 print("你好,这里是计算稀疏矩阵线性方程组的地方,非诚勿扰!") dism_num = input("你的A矩阵维数是:") dism_num = int(dism_num) print("接下来请你依次输入矩阵的行向量(注意只能输入英文逗号,):") A =[] #X =[] for i in range(1,dism_num+1): a=input("第"+str(i)+"行向量是:") alist = a.split(",") alist = [int(alist[j]) for j in range(len(alist))] A.append(alist) print("你所输入的矩阵行向量是:") print(A) #记录输入的X矩阵 #输入向量b print("输入b向量") b = input("b向量是:") b_list = b.split(",") b_list = [int(b_list[j]) for j in range(len(b_list))] print("你输入的b向量是:") print(b_list) #记录b向量 #询问是否计算单个答案(单元素) ask = input("是否只需求解单个值:(是或否)") while(True): if ask == '是': ask_a = 'T' ask_num = input("请继续输入你所需要的答案序号:") ask_num = int(ask_num) if ask_num<=dism_num and ask_num>0: print("OK,马上帮你计算") break else: print("输入的值超出矩阵维数,请重新输入:") if ask == '否': ask_a = 'F' break #询问完成,只有当用户输入正确的序号才可以进行计算,否则重新询问 #开始计算x向量了 A = np.array(A) b = np.array(b_list) x = linalg.solve(A,b) print("计算的结果的:") if ask_a == 'F': print(x) if ask_a =='T': print(x[ask_num-1]) #计算完x向量了 os.system("pause") #用于py文件结束玩暂停显示结果
其基本流程如图:
运行结果如下:
补充:python 多线程稀疏矩阵乘法
看代码吧~
import threading, time import numpy as np res = [] class MyThread(threading.Thread): def __init__(self,i,j,m1,m2): threading.Thread.__init__(self) self.x, self.y = i,j self.m1, self.m2 = m1, m2 def run(self): global res, lock if lock.acquire(): m1 = self.m1[self.m1[:,0]==self.x] m2 = self.m2[self.m2[:,1]==self.y] value = 0. for item1 in m1: for item2 in m2: if item1[1] == item2[0]: value += item1[2]*item2[2] res.append([self.x,self.y,value]) lock.release() if "__main__" == __name__: m1 = [[2,2],[0,0,1],[0,1,2],[1,0,3],[1,1,4]] m2 = [[2,3],[0,0,2],[0,2,1],[1,2,3],[1,1,4]] s1, s2 = m1[0], m2[0] assert s1[1]==s2[0], 'mismatch' m1_value = np.array(m1[1:]) m2_value = np.array(m2[1:]) rows, cols = s1[0], s2[1] res.append([rows, cols]) ThreadList = [] lock = threading.Lock() for i in range(rows): for j in range(cols): t = MyThread(i,j,m1_value,m2_value) ThreadList.append(t) for t in ThreadList: t.start() for t in ThreadList: t.join() print (res)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持hwidc。