线性代数行列式的计算方法(通过代数余子式计算)
程序员文章站
2022-07-12 14:00:05
...
permutation.h
/***********************************/
/*
Nonstandard Permutation header
Copyright (C) [email protected]情久小羊,#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;
}
};
然后继续递归得到结果
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;
}
上一篇: 线性代数 行列式性质、计算2
下一篇: C# 删除DataTable中的空行