线性代数行列式的计算方法(通过代数余子式计算)

 permutation.h

/***********************************/
/*
Nonstandard Permutation header
Copyright (C) 2021---@情久小羊,#Free
There is no data error check
*/
/***********************************/
#pragma once
#include<initializer_list>
#include <xutility>
#include <xstring>
#include<vector>
#include <stdexcept>
using std::vector;
using std::initializer_list;
class Permutation {
	int rank;//n阶行列式
	vector<vector<int>>data;
public:
	Permutation(int rank, vector<vector<int>> data) {
		if (data.size() != rank)throw std::range_error("行列式大小异常");
		for (int i = 0; i < data.size(); ++i) {
			if (data.at(i).size() != rank)throw std::range_error("行列式大小异常");
		}
		this->data = data;
		this->rank = rank;
	}
	Permutation(int rank, initializer_list<int>data_list) {
		if (data_list.size() != rank * rank)throw std::range_error("行列式大小异常");
		vector<int>v;
		for (auto i = data_list.begin(); i != data_list.end(); ++i) {
			v.push_back(*i);
			if (v.size() == rank) {
				this->data.push_back(v);
				v.clear();
			}
		}
		this->rank = rank;
	}
	void print_permutation() {
		for (auto i = this->data.begin(); i != this->data.end(); ++i) {
			for (auto j = i->begin(); j != i->end(); ++j) {
				cout << *j << " ";
			}
			cout << '\n';
		}
	}
	//计算余子式
	Permutation cal_Cofactor(int row,int col) {
		vector<int>row_data; vector<vector<int>>temp_data;
		for (int i = 0; i < this->rank; ++i) {
			if (i == row - 1)continue;
			for (int j = 0; j < this->rank; ++j) {
				if (j == col - 1)continue;
				row_data.push_back(this->data.at(i).at(j));
			}
			temp_data.push_back(row_data);
			row_data.clear();
		}
		return Permutation(this->rank - 1, temp_data);
	}
	//递归通过代数余子式计算
	int calculate() {
		int n = 0;
		if (this->rank == 1)return this->data.at(0).at(0);
		for (int i = 0; i < this->rank; ++i) {
			n += this->data.at(0).at(i) * pow(-1, i + 2) * this->cal_Cofactor(1, i + 1).calculate();
		}
		return n;
	}
};

 \left| \begin{array}{cccc} x_{11} & x_{12} & \cdots& x_{1n} \\ x_{2_1} & x_{22} & \cdots &x_{2n}\\ \vdots & \vdots & \ddots & \vdots \\ 3 & 3 & \cdots & x_{nn} \end{array} \right|

\sum_{i=1}^nx_{1i}A_{1i}\\

然后继续递归得到结果

 main.cpp

#include"permutation.h"
int main() {
   cout<< Permutation(4,
        { 3, -1, 0, 7,
          1, 0, 1, 5,
          2, 3, -3, 1,
          0, 0, 1, -2}).calculate()<<'\n';

    cout << "~~~~~~~~~~~~~~~~~~~~~~" << '\n';
    Permutation(1, { 1 }).print_permutation();
    return 0;
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值