distributed-computing/tasks/mironov-eo/lab_6/ConsoleApp1/ConsoleApp1/MatrixHelper.cs
2023-12-12 22:45:59 +03:00

178 lines
4.8 KiB
C#

using CommandLine;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static ConsoleApp1.MatrixHelper;
namespace ConsoleApp1
{
public class MatrixHelper
{
static readonly Random rand = new Random();
object lockObject = new object();
public double[,] RandomGenerateMatrix(int dimensionsCount)
{
double[,] result = new double[dimensionsCount, dimensionsCount];
for (int i = 0; i < dimensionsCount; i++)
{
for (int j = 0; j < dimensionsCount; j++)
{
result[i, j] = rand.NextDouble() * 10;
}
}
return result;
}
public double determinantOfMatrixGaus(double[,] mat)
{
int n = mat.GetLength(0);
int i, j, k;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (j == i)
continue;
double someDet = mat[j, i] / mat[i, i];
for (k = i; k < n; k++)
mat[j, k] -= someDet * mat[i, k];
}
}
double det = 1;
for (i = 0; i < n; i++)
det = det * mat[i, i];
return det;
}
public double determinantOfMatrixParallelGaus(double[,] mat, int threadCount)
{
int n = mat.GetLength(0);
Parallel.For(0, n - 1,
new ParallelOptions()
{
MaxDegreeOfParallelism = threadCount
},
(i) =>
{
for (int j = i + 1; j < n; j++)
{
if (j == i)
continue;
double det = mat[j, i] / mat[i, i];
for (int k = i; k < n; k++)
mat[j, k] = mat[j, k] - det * mat[i, k];
};
});
double det = 1;
for (int i = 0; i < n; i++)
det = det * mat[i, i];
return det;
}
public double determinantOfMatrixLaplas(double[,] matrix, int threadCount)
{
int size = matrix.GetLength(0);
if (size == 1)
{
return matrix[0, 0];
}
else if (size == 2)
{
return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
}
else
{
double determinant = 0;
Parallel.For(0, size,
new ParallelOptions
{
MaxDegreeOfParallelism = threadCount
},
(i) =>
{
double[,] subMatrix = GetSubMatrix(matrix, i);
double subDeterminant = matrix[0, i] * Determinant(subMatrix);
double value = Math.Pow(-1, i) * subDeterminant;
lock (lockObject)
{
determinant += value;
}
});
return determinant;
}
}
static double[,] GetSubMatrix(double[,] matrix, int columnIndex)
{
int size = matrix.GetLength(0);
double[,] subMatrix = new double[size - 1, size - 1];
for (int i = 1; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (j < columnIndex)
{
subMatrix[i - 1, j] = matrix[i, j];
}
else if (j > columnIndex)
{
subMatrix[i - 1, j - 1] = matrix[i, j];
}
}
}
return subMatrix;
}
static double Determinant(double[,] matrix)
{
int size = matrix.GetLength(0);
if (size == 1)
{
return matrix[0, 0];
}
else if (size == 2)
{
return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
}
else
{
double determinant = 0;
for (int i = 0; i < size; i++)
{
double[,] subMatrix = GetSubMatrix(matrix, i);
determinant += (int)Math.Pow(-1, i) * matrix[0, i] * Determinant(subMatrix);
}
return determinant;
}
}
}
}