0

我在一个通用类中有一个计算矩阵行列式的函数。该函数适用于任何类型的某些输入,而对于其他输入则给出错误的答案(基于类型)。

这是功能:

    public T Determinant()
    {
        checked
        {
            int n = dimension;
            Matrix<T> a = new Matrix<T>(baseArray);
            int i, j, k;
            T det = (dynamic)0;
            for (i = 0; i < n - 1; i++)
            {
                for (j = i + 1; j < n; j++)
                {
                    det = (dynamic)a[j, i] / a[i, i];
                    for (k = i; k < n; k++)
                        a[j, k] = a[j, k] - (dynamic)det * a[i, k];
                }
            }
            det = (dynamic)1;
            for (i = 0; i < n; i++)
                det = (dynamic)det * a[i, i];

            return det;
        }
    }

我添加了checked块以查看是否发生溢出,但显然没有发生溢出。

一个示例输入是,如果 baseArray 是new double[,] {{11, 11, 12, 17, 21, 29}, {16, 9, 25, 30, 29, 33}, {3, 13, 9, 24, 21, 24}, {23, 6, 29, 21, 23, 23}, {22, 19, 14, 30, 21, 24}, {22, 28, 20, 17, 25, 28}};,它将给出正确的答案(非常接近 -942755),但如果 baseArray 是,new int[,] {{11, 11, 12, 17, 21, 29}, {16, 9, 25, 30, 29, 33}, {3, 13, 9, 24, 21, 24}, {23, 6, 29, 21, 23, 23}, {22, 19, 14, 30, 21, 24}, {22, 28, 20, 17, 25, 28}};它会给出 15934050 作为答案(甚至不接近)。

矩阵上的索引器只返回矩阵的第 i 个第 j 个元素,所以它们不是问题。

我对可能是什么问题感到困惑,因为它不是溢出。有任何想法吗?

重现代码:

public class Matrix<T>
where T : IConvertible
{
    private int dimension;
    private T[][] baseArray;

    public Matrix(int dimensions, T[,] baseArray)
    {
        this.dimension = dimensions;
        this.baseArray = new T[dimension][];
        for (int i = 0; i < dimension; i++)
        {
            this.baseArray[i] = new T[dimension];
            for (int j = 0; j < dimension; j++)
            {
                this[i, j] = baseArray[i, j];
            }
        }
    }

    public T this[int a, int b]
    {
        get
        {
            return baseArray[a][b];
        }
        set
        {
            baseArray[a][b] = value;
        }
    }

    public T Determinant()
    {
        checked
        {
            int n = dimension;
            Matrix<T> a = new Matrix<T>(baseArray);
            int i, j, k;
            T det = (dynamic)0;
            for (i = 0; i < n - 1; i++)
            {
                for (j = i + 1; j < n; j++)
                {
                    det = (dynamic)a[j, i] / a[i, i];
                    for (k = i; k < n; k++)
                        a[j, k] = a[j, k] - (dynamic)det * a[i, k];
                }
            }
            det = (dynamic)1;
            for (i = 0; i < n; i++)
                det = (dynamic)det * a[i, i];

            return det;
        }
    }
}
4

1 回答 1

8

当值是int值时,它执行整数运算。当值是double值时,它会执行浮点运算——就这么简单。更简单的例子:

using System;

public class Test
{
    static void Main()
    {
        PrintResult(1, 2);      // Prints 0
        PrintResult(1.0, 2.0);  // Prints 0.5
    }

    static void PrintResult(dynamic x, dynamic y)
    {
        Console.WriteLine(x / y);
    }
}
于 2012-04-12T22:02:18.517 回答