Feat: hw2 done
This commit is contained in:
49
HW2_111550013/HW2_111550013_code/problem1.cpp
Normal file
49
HW2_111550013/HW2_111550013_code/problem1.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
// Problem 1: Gaussian elimination with partial pivoting
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <cmath>
|
||||
using namespace std;
|
||||
|
||||
const int N = 4;
|
||||
|
||||
int main() {
|
||||
double A[N][N+1] = {
|
||||
{4, 2, -2, -1, 7},
|
||||
{0, 4, 1, 2, 10},
|
||||
{3, -2, 1, 2, 2},
|
||||
{2, 0, 3, -5, 3}
|
||||
};
|
||||
|
||||
// Forward elimination with partial pivoting
|
||||
for (int k = 0; k < N - 1; k++) {
|
||||
// Find pivot
|
||||
int maxRow = k;
|
||||
for (int i = k + 1; i < N; i++)
|
||||
if (fabs(A[i][k]) > fabs(A[maxRow][k])) maxRow = i;
|
||||
|
||||
if (maxRow != k) {
|
||||
cout << "Column " << (k+1) << ": swap row " << (k+1) << " with row " << (maxRow+1) << "\n";
|
||||
for (int j = 0; j <= N; j++) swap(A[k][j], A[maxRow][j]);
|
||||
}
|
||||
|
||||
// Eliminate
|
||||
for (int i = k + 1; i < N; i++) {
|
||||
double m = A[i][k] / A[k][k];
|
||||
for (int j = k; j <= N; j++) A[i][j] -= m * A[k][j];
|
||||
}
|
||||
}
|
||||
|
||||
// Back substitution
|
||||
double x[N];
|
||||
for (int i = N - 1; i >= 0; i--) {
|
||||
x[i] = A[i][N];
|
||||
for (int j = i + 1; j < N; j++) x[i] -= A[i][j] * x[j];
|
||||
x[i] /= A[i][i];
|
||||
}
|
||||
|
||||
cout << "\nSolution:\n";
|
||||
for (int i = 0; i < N; i++)
|
||||
cout << "x" << (i+1) << " = " << fixed << setprecision(6) << x[i] << "\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user