c#parallel。用于高斯消除

时间:2014-11-05 07:02:50

标签: c# parallel-processing

我正在尝试使用并行处理(在这种情况下为Parallel.For)来解决中的高斯消元。我的代码有时运行正常,有时不运行。 我用链接上显示的代码作为起点:http://www.codeproject.com/Tips/388179/Linear-Equation-Solver-Gaussian-Elimination-Csharp。 我还没有使用Parallel.For进行背部插入,因为存在消除问题。

消除类:

public static bool Gauss(double[][] M)
    {
        int rowCount = (M.GetLength(0));
        int temp = rowCount - 1;

        //elimination
        Parallel.For(0, temp, sourceRow =>
        //for (int sourceRow = 0; sourceRow + 1 < rowCount; sourceRow++)//diagonal
        {

            for (int destRow = sourceRow + 1; destRow < rowCount; destRow++)//destination row
            {
                double df = M[sourceRow][sourceRow];
                double sf = M[destRow][sourceRow];

                for (int j = 0; j < rowCount + 1; j++) // line
                {
                    M[destRow][j] = (M[destRow][j] * df - M[sourceRow][j] * sf) / df;
                }
            }
        });

        //back-insertion
        for (int row = rowCount - 1; row >= 0; row--)
        {
            double f = M[row][row];
            if (f == 0) return false;

            for (int i = 0; i < rowCount + 1; i++) M[row][i] /= f;
            for (int destRow = 0; destRow < row; destRow++)
            {
                M[destRow][rowCount] -= M[destRow][row] * M[row][rowCount];
                M[destRow][row] = 0;
            }
        }
        return true;
    }

生成数组:

public static double[][] GenerateArray2(int n)
    {
        Random rnd = new Random();
        double[][] M = new double[n][];

        for (int i = 0; i < n; i++)
        {
            M[i] = new double[n + 1]; // Create inner array
            for (int j = 0; j < n + 1; j++)
                M[i][j] = rnd.Next(-20, 20);
        }
        return M;
    }

打印阵列

public static string Print2(double[][] M)
    {
        string str = "";
        int rowCount = M.GetUpperBound(0) + 1;
        for (int row = 0; row < rowCount; row++)
        {
            for (int i = 0; i <= rowCount; i++)
            {
                str += M[row][i];
                str += "\t";
            }
            str += Environment.NewLine;
        }
        return str;
    }

矩阵16x17及以上的结果是错误的。此时我不知道如何继续,我试图锁定M消除,没有帮助。

感谢您的帮助。

0 个答案:

没有答案
相关问题