我有一个相当基本的数学问题,但诀窍是我在 C++ 中需要它。我现在正在关注维基百科上给出的伪代码。这是我的尝试:
createMatrixForAllSolutions(*this);
std::cout << equationMatrix.to_string() << endl;
bool solved = false;
int rows = equationMatrix.getRows();
int cols = equationMatrix.getCols();
int i = 0;
int j = 0;
int maxi = 0;
double current = 0;
double eqnValue = 0;
double solValue = 0;
std::vector<char> reversedVars;
int sum = 0;
int tempValue;
int tempRHS;
int newValue;
int neRHS;
while (i < rows && j < cols) {
maxi = i;
for (int k = i + 1; k < rows; k++) {
if (abs(equationMatrix.get_element(k, j)) > abs(equationMatrix.get_element(maxi, j)))
maxi = k;
}
if (equationMatrix.get_element(maxi, j) != 0) {
current = equationMatrix.get_element(i, j);
for (int x = 0; x < cols; x++) {
tempValue = equationMatrix.get_element(i, x);
newValue = equationMatrix.get_element(maxi, x);
equationMatrix.set_element(i, x, newValue/current);
equationMatrix.set_element(maxi, x, tempValue);
}
tempRHS = solutionMatrix.get_element(i, 0);
neRHS = solutionMatrix.get_element(maxi, 0);
solutionMatrix.set_element(i, 0, neRHS/current);
solutionMatrix.set_element(maxi, 0, tempRHS);
//SWAP rows i and maxi
//SWAP RHS i and maxi
//DIVIDE each entry in row i by current
//DIVIDE RHS i by current
for (int u = i + 1; u < rows; u++) {
eqnValue = equationMatrix.get_element(u, j) - equationMatrix.get_element(i, j) * equationMatrix.get_element(u, j);
std::cout << "Equation Value: " << eqnValue << endl;
equationMatrix.set_element(u, j, eqnValue);
solValue = solutionMatrix.get_element(u, 0) - solutionMatrix.get_element(i, 0) * solutionMatrix.get_element(u, 0);
std::cout << "Solution Value: " << solValue << endl;
solutionMatrix.set_element(u, 0, solValue);
}
i++;
}
j++;
}
我关注的伪代码来自维基百科:
i := 1
j := 1
while (i ≤ m and j ≤ n) do
Find pivot in column j, starting in row i:
maxi := i
for k := i+1 to m do
if abs(A[k,j]) > abs(A[maxi,j]) then
maxi := k
end if
end for
if A[maxi,j] ≠ 0 then
swap rows i and maxi, but do not change the value of i
Now A[i,j] will contain the old value of A[maxi,j].
divide each entry in row i by A[i,j]
Now A[i,j] will have the value 1.
for u := i+1 to m do
subtract A[u,j] * row i from row u
Now A[u,j] will be 0, since A[u,j] - A[i,j] * A[u,j] = A[u,j] - 1 * A[u,j] = 0.
end for
i := i + 1
end if
j := j + 1
end while
到目前为止,我已经做到了最好的匹配,但是如果有人能够弄清楚为什么我的母鹿不工作,那就太好了。谢谢!