class matrix {
private:
int row; // 행
int column; // 열
std::vector<std::vector<double>> elements; // 데이터
이렇게 생긴 행렬 클래스를 이용해서 가우스조던소거법으로 행렬식을 구하는 함수를 만들어봤습니다
근데 이게 잘 작동하긴 하는데 코드를 보면 눈이 썩습니다;
코드 압축하는거 도와주십시오 아직 예외도 안던졋는데 코드가 이지경입니다
double matrix::determinant(void) {
double mass = 1;
matrix temp = *this;
auto current_row = temp.elements.begin();
int current_column = 0;
while (current_column < temp.column) {
double* pivot = NULL;
for (int i = current_row - temp.elements.begin(); i < temp.row; ++i) {
if (temp.elements[i][current_column] != 0) {
pivot = &temp.elements[i][current_column];
double scalar = *pivot;
mass *= *pivot;
std::transform(temp.elements[i].begin(), temp.elements[i].end(),
temp.elements[i].begin(), [&scalar](double v_) -> double {return v_ / scalar; });
if (temp.elements[i] != *current_row) {
mass *= -1;
temp.elements[i].swap(*current_row);
}
break;
}
}
if (pivot == NULL) {
++current_column;
continue;
}
for (int i = 0; i < temp.row; ++i) {
if (temp.elements[i] == *current_row) {
continue;
}
double scalar = temp.elements[i][current_column];
std::transform((*current_row).cbegin(), (*current_row).cend(), temp.elements[i].cbegin(),
temp.elements[i].begin(), [&scalar](const double& v_, const double& w_) -> double {
return w_ - scalar * v_;
});
}
++current_row;
++current_column;
}
double diagonal_product = 1;
for (int i = 0; i < temp.row; ++i) {
diagonal_product *= temp[i][i];
}
return mass * diagonal_product;
}
댓글 0