⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 matrix_qr.cpp

📁 我这个程序实现了数值线性代数里面的QR分解
💻 CPP
字号:
//date:31/10/07   by:TG
#include<iostream>
#include<istream>
#include<ostream>
#include<exception>
#include<cmath>

const int N(100);
typedef double type;

void input_A(std::istream&data_source,type A[][N],int m,int n);
void output(std::ostream&out,type L[][N],int m,int n);
void calculating_QR(int m,int n,type A[][N],type Q[][N],type R[][N]);

int main(){
	try{
		type A[N][N],Q[N][N],R[N][N];
		std::cout<<"请输入矩阵A的行数:"<<'\n';
		int m(0);
		std::cin>>m;
		std::cout<<"请输入矩阵A的列数:"<<'\n';
		int n(0);
		std::cin>>n;
		input_A(std::cin,A,m,n);
		std::cout<<"您输入的矩阵A为:"<<'\n';
		output(std::cout,A,m,n);
		calculating_QR(m,n,A,Q,R);
		std::cout<<"得到的矩阵Q为:"<<'\n';
		output(std::cout,Q,m,n);
		std::cout<<"得到的矩阵R为:"<<'\n';
		output(std::cout,R,n,n);
	}
	catch(...){
		std::cerr<<"***An exception was thrown.***\n";
	}
}

void input_A(std::istream&in,type A[][N],int m,int n){
	for(int i(0);i!=m;++i){
		for(int j(0);j!=n;++j){
			std::cout<<"请输入第"<<i<<"行第"<<j<<"列的元素:";
			in>>A[i][j];
			std::cout<<'\n';
		}
	}
}
void output(std::ostream&out,type L[][N],int m,int n){
	for(int i(0);i!=m;++i){
		for(int j(0);j!=n;++j){
			out<<L[i][j]<<" ";
		}
		std::cout<<'\n';
	}
}
void calculating_QR(int m,int n,type A[][N],type Q[][N],type R[][N]){
	type sum2(0);
	for(int c(0);c!=m;++c){
		sum2+=A[c][0]*A[c][0];
	}
	R[0][0]=std::sqrt(sum2);
	for(int i(0);i!=n;++i){
		for(int p(0);p!=m;++p){
			Q[p][i]=A[p][i]/R[i][i];
		}
			for(int b(i+1);b!=n;++b){
			type sum1(0);
			for(int a(0);a!=m;++a){
				sum1+=Q[a][i]*A[a][b];
			}
			R[i][b]=sum1;
			for(int a(0);a!=m;++a){
				A[a][b]=A[a][b]-R[i][b]*Q[a][i];
			}
			}
		
			type sum(0);
			for(int z(0);z!=m;++z){
				sum+=A[z][i+1]*A[z][i+1];
			}
			R[i+1][i+1]=std::sqrt(sum);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -