c# – double [,] vs. List>
发布时间:2020-12-16 01:33:12 所属栏目:百科 来源:网络整理
导读:我有使用double [,]的矩阵乘法实验室的代码,我想将它与使用List的实现进行比较.列表与LT;双 public static Matrix operator *(Matrix a,Matrix b) { if (a.Width != b.Height) { throw new InvalidOperationException(); } double[,] result = new double[a.
我有使用double [,]的矩阵乘法实验室的代码,我想将它与使用List<的实现进行比较.列表与LT;双>>
public static Matrix operator *(Matrix a,Matrix b) { if (a.Width != b.Height) { throw new InvalidOperationException(); } double[,] result = new double[a.Height,b.Width]; for (int i = 0; i < a.Height; i++) { for (int j = 0; j < b.Width; j++) { for (int k = 0; k < a.Width; k++) result[i,j] += a[i,k] * b[k,j]; } } return new Matrix(result); } ‘结果’这里有正确的数据: 输入矩阵A: 1.000 2.000 3.000 1.000 2.000 3.000 3.000 1.000 输入矩阵B: 1.000 0.000 0.000 0.000 0.000 1.000 0.000 0.000 0.000 0.000 1.000 0.000 2.000 3.000 0.000 1.000 矩阵产品A * B. 3.000 5.000 3.000 1.000 4.000 6.000 3.000 1.000 将其更改为列表… public List<List<double>> matrix; public double this[int x,int y] { get { return matrix[x][y]; } set { matrix[x][y] = value; } } public static Matrix operator *(Matrix a,Matrix b) { if (a.Width != b.Height) { throw new InvalidOperationException(); } Matrix result = new Matrix(a.Height,b.Width); for (int i = 0; i < a.Height; i++) { for (int j = 0; j < b.Width; j++) { for (int k = 0; k < a.Width; k++) result[i,j]; } } return result; } 现在使用相同的数据结果: [7] [11] [6] [2] [7] [11] [6] [2] 编辑:构造函数是: public Matrix(int height,int width) { List<List<double>> points = new List<List<double>>(); List<double> row = new List<double>(); for (int i = 0; i < width; i++) { row.Add(0.0d); } for (int i = 0; i < height; i++) { points.Add(row); } matrix = points; } 看起来它工作正常,everythign初始化为0.0 我的问题是为什么数学在存储值的两种方式之间发生变化. 解决方法
问题出在你的矩阵构造函数中.您将“点”中的每个“行”设置为同一个实例.
尝试将构造函数更改为: public Matrix(int height,int width) { List<List<double>> points = new List<List<double>>(height); // Might as well set the default capacity... for (int j = 0; j < height; j++) { List<double> row = new List<double>(width); for (int i = 0; i < width; i++) { row.Add(0.0d); } points.Add(row); } matrix = points; } 话虽这么说,对于矩阵,除非你试图实现稀疏矩阵,否则多维数组更有意义.仅当您希望允许列表增长时,使用列表列表才会更有意义.在您的情况下,您事先知道大小,因此使用数组可能是更好的选择. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |