public void SecondEquationTest() { Matrix variableCoefficients = new Matrix(new float[, ] { { 2, -1, -1 }, { 1, 3, -2 }, { 1, 2, 3 } }); Matrix freeCoefficients = new Matrix(new float[, ] { { 5 }, { 7 }, { 10 } }); Matrix expectedResult = new Matrix(new float[, ] { { 61f / 16f }, { 27f / 16f }, { 15f / 16f } }); Matrix result = GaussMethod.Solve(variableCoefficients, freeCoefficients); Assert.True(expectedResult.NearEquals(result), "Matrices are not equal:\nExpected:{0}\nResult:{1}", expectedResult.ToString(), result.ToString()); }
public void ThirdEquationTest() { Matrix variableCoefficients = new Matrix(new float[, ] { { 8, 5, 3 }, { -2, 8, 1 }, { 1, 3, -10 } }); Matrix freeCoefficients = new Matrix(new float[, ] { { 30 }, { 15 }, { 42 } }); Matrix expectedResult = new Matrix(new float[, ] { { 3f }, { 3f }, { -3f } }); Matrix result = GaussMethod.Solve(variableCoefficients, freeCoefficients); Assert.True(expectedResult.NearEquals(result), "Matrices are not equal:\nExpected:{0}\nResult:{1}", expectedResult.ToString(), result.ToString()); }
private void ComputeParameters() { Lambda.ForEach(lambdas => Lambda0.AddElement(lambdas.Sum())); RoTotal = new Vector <double>(NodesCount); for (int stream = 0; stream < StreamsCount; stream++) { // input intensity InputProbability.Add(Lambda[stream].Clone().InsertElement(0, 0).Divide(Lambda0[stream])); // E E.Add(GaussMethod.Solve(GetExtendedMatrix(stream))); // lambda' LambdaBar.Add(E[stream].Multiply(Lambda0[stream])); // ro' & ro total RoBar.Add(LambdaBar[stream].DivideElementWise(Mu[stream])); RoTotal = RoTotal.AddElementWise(RoBar.Last()); if (RoBar[stream].Any(roBar => roBar > 1)) { throw new ArgumentOutOfRangeException(string.Format("RoBar, stream {0}", stream), "Some Ro' is greater than zero."); } } if (RoTotal.Any(roTotal => roTotal > 1)) { throw new ArgumentOutOfRangeException("RoTotal", "Some RoTotal is greater than zero."); } FindPaths(); }
public void FirstEquationTest() { // Currently used for debug purposes Matrix variableCoefficients = new Matrix(new float[, ] { { 1, -2, 1 }, { 2, -5, -1 }, { -7, 0, 1 } }); Matrix freeCoefficients = new Matrix(new float[, ] { { 2 }, { -1 }, { -2 } }); Matrix expectedResult = new Matrix(new float[, ] { { 13f / 25f }, { 2f / 25f }, { 41f / 25f } }); Matrix result = GaussMethod.Solve(variableCoefficients, freeCoefficients); Assert.True(expectedResult.NearEquals(result), "Matrices are not equal:\nExpected:{0}\nResult:{1}", expectedResult.ToString(), result.ToString()); }
private void button_solve_Click(object sender, EventArgs e) { int serverCount = DEFAULT_SERVER_COUNT; try { serverCount = int.Parse(server_count.Text); } catch (Exception exc) { } try { GaussStatisticsMaker gaussStatisticsMaker = new GaussStatisticsMaker(matrix, 1, 2, 3, 4); gaussStatisticsMaker.MakeStatistic(); gaussStatistics = gaussStatisticsMaker.GetWorkStatistic(); DrawChart(); GaussMethod gaussMethod = new GaussMethod(matrix); gaussMethod.Solve(); VectorInterface <double> result = gaussMethod.GetSolution(); FileHandler.WriteMatrix(matrix); FileHandler.WriteSolution(result); } catch (Exception exc) { } }
/// <summary> /// LU метод решения СЛУ. /// </summary> /// <param name="Source"></param> /// <returns></returns> public static Vector Solve(Matrix Source) { Matrix[] buffer = GetLU(Source); Matrix L = buffer[0]; Matrix U = buffer[1]; Vector Y = GaussMethod.Solve(new Matrix(L.Values.Select((row, index) => row.Concat(new[] { Source[index].Last() }).ToArray()).ToArray())); Vector X = GaussMethod.Solve(new Matrix(U.Values.Select((row, index) => row.Concat(new[] { Y[index] }).ToArray()).ToArray())); return(X); }
public void Variables_3_matrix_solve() { VectorInterface <Double> expected = new DoubleVector(-2f / 11.0, 1f / 11.0, 5f / 11.0); GaussMethod gaussMethod = new GaussMethod(new Double[][] { new double[] { 3.0, 2.0, 3.0, 1.0 }, new double[] { 4.0, 4.0, 3.0, 1.0 }, new double[] { 1.0, 4.0, 4.0, 2.0 } }); gaussMethod.Solve(); VectorInterface <Double> actual = gaussMethod.GetSolution(); Assert.AreEqual(expected, actual); }
private void TestFile(string testName) { VectorInterface <Double> expected = new DoubleVector( Parser.parseVector(FileHandler.Read("tests/" + testName + "/" + testName + ".des"))); DoubleMatrix doubleMatrix = new DoubleMatrix( Parser.parseMatrix(FileHandler.Read("tests/" + testName + "/" + testName + ".A"))); doubleMatrix.UpendColumn(new DoubleVector( Parser.parseVector(FileHandler.Read("tests/" + testName + "/" + testName + ".B")))); GaussMethod gaussMethod = new GaussMethod(doubleMatrix); gaussMethod.Solve(); VectorInterface <Double> actual = gaussMethod.GetSolution(); Assert.AreEqual(expected, actual); }
public static void Main(string[] args) { gaussMethod = new GaussMethod(num, num); gaussMethod.RandomInit(gaussMethod.rowCount, gaussMethod.columCount); // Create a Http server and start listening for incoming connections listener = new HttpListener(); listener.Prefixes.Add(url); listener.Start(); Console.WriteLine(DateTime.Now.ToString() + " - Listening for connections on {0}", url); try { Console.Write(DateTime.Now.ToString() + " - Enter client's count: "); clientCount = Int32.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine(DateTime.Now.ToString() + " - Input error... Repeat one more time..."); } Console.WriteLine(DateTime.Now.ToString() + " - Waiting for connections"); // Handle requests Task listenTask = HandleIncomingConnections(clientCount); listenTask.GetAwaiter().GetResult(); listenTask.Wait(); Task sendMatrixTask = HandleMatrixSend(clientCount); sendMatrixTask.GetAwaiter().GetResult(); // Close the listener listener.Close(); Console.ReadKey(); }
public KeyValuePair <double, double>[] Solve(BoundaryValueTask task, int n) { double[,] matrix = new double[n + 1, n + 1]; double[] vect = new double[n + 1]; double h = (task.b - task.a) / n; vect[0] = task.A * h; vect[n] = task.B * h; matrix[0, 0] = task.alpha0 * h - task.alpha1; matrix[0, 1] = task.alpha1; matrix[n, n] = task.betta0 * h + task.betta1; matrix[n, n - 1] = -task.betta1; for (int i = 1; i <= n - 1; i++) { double xi = task.a + i * h; vect[i] = 2 * Math.Pow(h, 2) * task.FX.Calculate(xi); matrix[i, i + 1] = 2 + task.PX.Calculate(xi) * h; matrix[i, i] = task.QX.Calculate(xi) * 2 * Math.Pow(h, 2) - 4; matrix[i, i - 1] = 2 - task.PX.Calculate(xi) * h; } Vector yx = new GaussMethod().Solve(new SLAE(matrix, vect)); KeyValuePair <double, double>[] result = new KeyValuePair <double, double> [yx.Count]; for (int i = 0; i < result.Length; i++) { result[i] = new KeyValuePair <double, double>(task.a + i * h, yx[i]); } return(result); }
static async Task Main(string[] args) { try { Console.Write(DateTime.Now.ToString() + " - Enter nickname: "); nickname = Console.ReadLine(); HttpClient httpClient = new HttpClient(); HttpResponseMessage status = await httpClient.GetAsync(url); switch (status.StatusCode) { case HttpStatusCode.OK: Console.WriteLine(DateTime.Now.ToString() + " - Клиент подключен к серверу по адресу - " + url); break; case HttpStatusCode.Forbidden: Console.WriteLine(DateTime.Now.ToString() + " - У клиента отсутствует доступ к серверу по адресу - " + url); break; case HttpStatusCode.NotFound: Console.WriteLine(DateTime.Now.ToString() + " - Сервер по адресу - " + url + " не найден"); break; case HttpStatusCode.ServiceUnavailable: Console.WriteLine(DateTime.Now.ToString() + " - Сервер по адресу - " + url + " недоступен"); break; default: break; } HttpResponseMessage msg = await httpClient.PostAsync(url, new StringContent(nickname, Encoding.UTF8)); string result = msg.Content.ReadAsStringAsync().Result; Console.WriteLine(DateTime.Now.ToString() + " - " + result); byte[] content = await httpClient.GetByteArrayAsync(url); BinaryFormatter binaryFormatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(content)) { gaussMethod = (GaussMethod)binaryFormatter.Deserialize(stream); } gaussMethod.SolveMatrix(); Console.WriteLine(gaussMethod.ToString()); /*string content = await httpClient.GetStringAsync(url); * Console.WriteLine(content);*/ } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); }
/// <summary> /// Установить решение СЛАУ /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="type"></param> /// <returns></returns> public static double[] GetSLAUResolve(double[][] a, double[] b, GaussMethod type) { a = MatrixOperations.Copy(a); b = MatrixOperations.Copy(b); int varCount = a.Length; const double epsilon = 0.00000000000001; //точность нуля int[] perm = null; if (type == GaussMethod.Rows || type == GaussMethod.All) { perm = Enumerable.Range(0, b.Length).ToArray(); //перестановка } for (int k = 0; k < varCount; k++) { switch (type) { //выбор ведущего (максимального) элемента по столбцу case GaussMethod.Cols: int index = k; double max = Math.Abs(a[k][k]); for (int i = k + 1; i < varCount; i++) { if (Math.Abs(a[i][k]) > max) { max = Math.Abs(a[i][k]); index = i; } } if (max < epsilon) { throw new Exception("Нет ненулевых диагональных элементов"); } Swap(ref a[k], ref a[index]); Swap(ref b[k], ref b[index]); break; //выбор ведущего (максимального) элемента по строке case GaussMethod.Rows: index = k; max = Math.Abs(a[k][k]); for (int i = k + 1; i < varCount; i++) { if (Math.Abs(a[k][i]) > max) { max = Math.Abs(a[k][i]); index = i; } } if (max < epsilon) { throw new Exception("Нет ненулевых диагональных элементов"); } SwapCols(ref a, k, index); Swap(ref perm[k], ref perm[index]); break; //выбор ведущего (максимального) элемента по всей матрице case GaussMethod.All: int nRow = k, nCol = k; max = Math.Abs(a[k][k]); for (int i = k; i < varCount; i++) { for (int j = k; j < varCount; j++) { if (Math.Abs(a[i][j]) > max) { max = Math.Abs(a[i][j]); nRow = i; nCol = j; } } } if (max < epsilon) { throw new Exception("Нет ненулевых диагональных элементов"); } Swap(ref a[k], ref a[nRow]); Swap(ref b[k], ref b[nRow]); SwapCols(ref a, k, nCol); Swap(ref perm[k], ref perm[nCol]); break; } //Приведение к треугольному виду double temp = a[k][k]; for (int j = k; j < varCount; j++) { a[k][j] = a[k][j] / temp; } b[k] = b[k] / temp; for (int i = k + 1; i < varCount; i++) { temp = a[i][k]; if (Math.Abs(a[i][k]) < epsilon) { continue; // для нулевого коэффициента пропустить } for (int j = k; j < varCount; j++) { a[i][j] = a[k][j] * temp - a[i][j]; } b[i] = b[k] * temp - b[i]; } } //нахождение x double[] x = new double[varCount]; for (int k = varCount - 1; k >= 0; k--) { x[k] = b[k]; for (int i = 0; i < k; i++) //пробег по столбцам до k-1 { b[i] = b[i] - a[i][k] * x[k]; } } //Учитываем перестановку вектора x if (type == GaussMethod.Rows || type == GaussMethod.All) { double[] temp = new double[x.Length]; for (int i = 0; i < perm.Length; i++) { temp[perm[i]] = x[i]; } x = temp; } return(x); }
public void Illegal_matrix_initialize_throw_exception() { GaussMethod gaussMethod = new GaussMethod(new Double[][] { new double[] { 3.0, 2.0, 3.0 }, new double[] { 4.0, 4.0, 3.0 }, new double[] { 1.0, 4.0, 4.0 } }); }
static void Test(int iterations, Matrix variableCoefficients, Matrix freeCoefficients) { float epsilon = 0.0001f; float relaxationWeight = 0.8f; var stopwatch = new Stopwatch(); Console.Write("######################################################\nSelect the algorithm:\n1.Gauss\n2.Jacobi\n3.Gauss-Seidel\n4.Relaxation\nEnter the choice:"); int algorithm = Convert.ToInt32(Console.ReadLine()); switch (algorithm) { case 1: { stopwatch.Start(); for (int i = 0; i < iterations; i++) { var result = GaussMethod.Solve(Matrix.Clone(variableCoefficients), Matrix.Clone(freeCoefficients)); } stopwatch.Stop(); Console.WriteLine("Total elapsed time: " + stopwatch.Elapsed + "\n######################################################"); break; } case 2: { stopwatch.Start(); for (int i = 0; i < iterations; i++) { var result = JacobiMethod.Solve(Matrix.Clone(variableCoefficients), Matrix.Clone(freeCoefficients), epsilon); } stopwatch.Stop(); Console.WriteLine("Total elapsed time: " + stopwatch.Elapsed); break; } case 3: { stopwatch.Start(); for (int i = 0; i < iterations; i++) { var result = GaussZeidelMethod.Solve(Matrix.Clone(variableCoefficients), Matrix.Clone(freeCoefficients), epsilon); } stopwatch.Stop(); Console.WriteLine("Total elapsed time: " + stopwatch.Elapsed); break; } case 4: { stopwatch.Start(); for (int i = 0; i < iterations; i++) { var result = RelaxationMethod.Solve(Matrix.Clone(variableCoefficients), Matrix.Clone(freeCoefficients), epsilon, relaxationWeight); } stopwatch.Stop(); Console.WriteLine("Total elapsed time: " + stopwatch.Elapsed); break; } } }
public CollocationMethod() { method = new GaussMethod(); }
static void Main(string[] args) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); GaussMethod gauss = new GaussMethod(num, num); gauss.RandomInit(num, num); Task <string> rightStringTask = new Task <string>(() => GaussMethod.ArrayToString(gauss.rightPart)); Task <string> matrixStringTask = new Task <string>(() => GaussMethod.MatrixToString(gauss.matrix)); Task[] tasks1 = new Task[2] { rightStringTask, matrixStringTask }; for (int i = 0; i < tasks1.Length; i++) { tasks1[i].Start(); } Task.WaitAll(tasks1); Task first = TextFileHandler.WriteToFile(TextFileHandler.RIGHT_PART_FILE, rightStringTask.Result); Task second = TextFileHandler.WriteToFile(TextFileHandler.MATRIX_FILE, matrixStringTask.Result); Task third = TextFileHandler.WriteSizeInfoToFile(TextFileHandler.SIZE_INFO_FILE, gauss); Task[] tasks2 = new Task[3] { first, second, third }; for (int i = 0; i < tasks2.Length; i++) { tasks2[i].GetAwaiter().GetResult(); } Task.WaitAll(tasks2); GaussMethod gaussMethod = null; Task <GaussMethod> info = new Task <GaussMethod>(() => TextFileHandler.ReadSizeInfoFromFile(TextFileHandler.SIZE_INFO_FILE)); info.Start(); info.Wait(); gaussMethod = info.Result; Task fouth = TextFileHandler.ReadArraytFromFile(TextFileHandler.RIGHT_PART_FILE, gaussMethod.rightPart); Task fifth = TextFileHandler.ReadMatrixFromFile(TextFileHandler.MATRIX_FILE, gaussMethod.matrix); Task[] tasks3 = new Task[2] { fouth, fifth }; for (int i = 0; i < tasks3.Length; i++) { tasks3[i].GetAwaiter().GetResult(); } Task.WaitAll(tasks3); //Console.WriteLine(GaussMethod.ArrayToString(gaussMethod.rightPart)); //Console.WriteLine(GaussMethod.MatrixToString(gaussMethod.matrix)); gaussMethod.SolveMatrix(); Task sixth = TextFileHandler.WriteToFile(TextFileHandler.RESULT_FILE, GaussMethod.ArrayToString(gaussMethod.result)); sixth.GetAwaiter().GetResult(); //Console.WriteLine(gaussMethod.ToString()); stopwatch.Stop(); TimeSpan ts = stopwatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00000000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime: " + elapsedTime); Console.ReadKey(); }