Программа перемножения матриц, используя многопоточность - C#

Узнай цену своей работы

Формулировка задачи:

можете помочь с задачей: Напишите программу перемножения матриц, используя многопоточность. Размер матриц задаются пользователем, содержимое - случайным образом. Количества потоков так же задаются пользователем.

Решение задачи: «Программа перемножения матриц, используя многопоточность»

textual
Листинг программы
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Cg1Model
  8. {
  9.     public class Matrix : IEnumerable<double>
  10.     {
  11.         const string DimentionExceptionMessage = "Invalid matrix dimentions";
  12.         public static Matrix GetE(int n)
  13.         {
  14.             var result = new Matrix(n, n);
  15.             for (int i = 0; i < n; i++)
  16.             {
  17.                 result[i, i] = 1.0;
  18.             }
  19.             return result;
  20.         }
  21.  
  22.         private readonly double[,] _value;
  23.  
  24.         public Matrix(int rows, int cols)
  25.             : this(new double[rows, cols])
  26.         {
  27.         }
  28.  
  29.         public Matrix(double[,] value)
  30.         {
  31.             _value = (double[,])value.Clone();
  32.         }
  33.  
  34.         public static Matrix operator *(Matrix one, Matrix other)
  35.         {
  36.             return new Matrix(Multiply(one._value, other._value));
  37.         }
  38.  
  39.         public static Matrix operator *(double scalar, Matrix matrix)
  40.         {
  41.             var result = (double[,]) matrix._value.Clone();
  42.             for (int i = 0; i < result.GetLength(0); i++)
  43.             {
  44.                 for (int j = 0; j < result.GetLength(1); j++)
  45.                 {
  46.                     result[i, j] *= scalar;
  47.                 }
  48.             }
  49.             return result;
  50.         }
  51.  
  52.         public static Matrix operator *(Matrix matrix, double scalar)
  53.         {
  54.             return scalar * matrix;
  55.         }
  56.  
  57.         public static Matrix operator +(Matrix one, Matrix another)
  58.         {
  59.             return GetMatrix(one, another, 1);
  60.         }
  61.  
  62.         public static Matrix operator -(Matrix one, Matrix another)
  63.         {
  64.             return GetMatrix(one, another, -1);
  65.         }
  66.  
  67.         private static Matrix GetMatrix(Matrix one, Matrix another, int sign)
  68.         {
  69.             var m = GetDim(one, another, 0);
  70.             int n = GetDim(one, another, 1);
  71.             var res = new double[m, n];
  72.             for (int i = 0; i < m; i++)
  73.             {
  74.                 for (int j = 0; j < n; j++)
  75.                 {
  76.                     res[i, j] = one[i, j] + another[i, j]*sign;
  77.                 }
  78.             }
  79.             return new Matrix(res);
  80.         }
  81.  
  82.         private static int GetDim(Matrix one, Matrix another, int dim)
  83.         {
  84.             int dimOne = one._value.GetLength(dim);
  85.             int dimAnother = another._value.GetLength(dim);
  86.  
  87.             if (dimOne != dimAnother)
  88.             {
  89.                
  90.                 throw new ArgumentException(DimentionExceptionMessage);
  91.             }
  92.             return dimOne;
  93.         }
  94.  
  95.         public static Matrix operator /(Matrix matrix, double scalar)
  96.         {
  97.             return matrix*(1.0/scalar);
  98.         }
  99.  
  100.         public double this[int i, int j]
  101.         {
  102.             get { return _value[i,j]; }
  103.             set { _value[i,j ] = value; }
  104.         }
  105.  
  106.         public IEnumerator<double> GetEnumerator()
  107.         {
  108.             // ReSharper disable once LoopCanBeConvertedToQuery
  109.             foreach (double d in _value)
  110.             {
  111.                 yield return d;
  112.             }
  113.         }
  114.  
  115.         IEnumerator IEnumerable.GetEnumerator()
  116.         {
  117.             return GetEnumerator();
  118.         }
  119.  
  120.         public static implicit operator Matrix(double[,] doubles)
  121.         {
  122.             return new Matrix(doubles);
  123.         }
  124.  
  125.         public static explicit operator double[,](Matrix matrix)
  126.         {
  127.             return matrix._value;
  128.         }
  129.  
  130.         [MethodImpl(MethodImplOptions.AggressiveInlining)]
  131.         private static double[,] Multiply(double[,] a, double[,] b)
  132.         {
  133.             if (a.GetLength(1) != b.GetLength(0))
  134.                 throw new ArgumentException(DimentionExceptionMessage);
  135.             var result = new double[a.GetLength(0), b.GetLength(1)];
  136.             Parallel.For(0, a.GetLength(0),i =>
  137.                          {
  138.                              for (int j = 0; j < b.GetLength(1); j++)
  139.                                  result[i, j] = MultiplyR(a, b, i, j);
  140.                          });
  141.             return result;
  142.         }
  143.  
  144.         [MethodImpl(MethodImplOptions.AggressiveInlining)]
  145.         private static double MultiplyR(double[,] a, double[,] b, int i, int j)
  146.         {
  147.             double result = 0;
  148.             for (int k = 0; k < a.GetLength(1); k++)
  149.                 result += a[i, k] * b[k, j];
  150.             return result;
  151.         }
  152.  
  153.         public int GetLength(int dim)
  154.         {
  155.             return _value.GetLength(dim);
  156.         }
  157.     }
  158. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 3.8 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы