gpt4 book ai didi

c# - 前向消除实现的问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:29:01 25 4
gpt4 key购买 nike

让下面的C#

前向消除实现
public static void ForwardElimination(double[,] AugmentedMatrix)
{
int N = AugmentedMatrix.GetLength(0);

for (int k = 0; k < N; k++)
{
for (int i = k + 1; i < N; i++)
{
double factor = AugmentedMatrix[i, k] / AugmentedMatrix[k, k];

for (int j = k; j < N; j++)
{
AugmentedMatrix[i, j] -= factor * AugmentedMatrix[k, j];
}
}
}
}

上面实现的伪代码是:

enter image description here

使用NUnit测试

public void TestOfForwardElimination()
{
double[,] array = new double[,] { { 1, 2, 3 }, { 4, 5, 6 } };
NumericalMethods.ForwardElimination(array);
Assert.That(array, Is.EqualTo(new double[,] { { 1, 2, 3 }, { 0, -3, -6 } }));
}

有如下错误值

Message: 
Expected and actual are both <System.Double[2,3]>
Values differ at index [1,2]
Expected: -6.0d
But was: 6.0d

代码哪里出错了,如何修复?

最佳答案

您的解决方案中的问题是这一行。在这里,您必须遍历所有列,因此它应该是 j <= N,而不是 j < N。N 是 2,即行数,因此您的解决方案中缺少一次迭代。

for (int j = k; j <= N; j++)

您粘贴的算法适用于方阵 N x N 而不是 N x M,即您的情况 ( 2 x 3 )。如果是方阵就好了。

这是另一种看法@Petro - 你可以做的是创建 2 个变量,一个用于行,一个用于列。

int m = AugmentedMatrix.GetLength(0);
int n = AugmentedMatrix.GetLength(1);

对于前 2 个循环,它将是 m,对于最后一个循环,使用 n,即

for (int k = 0; k < m; k++)
for (int i = k + 1; i < m; i++)

最后一个

for (int j = k; j < n; j++)

此外,如果 m > n,这将不起作用。还在每次迭代中打印 i、j、k 以调试和捕获范围,例如

Console.WriteLine("i:" + i + ", k:" + k + ", factor: " + factor);

关于c# - 前向消除实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com