From 2d44405e9f934613a1734e7fc60c924b478d7c27 Mon Sep 17 00:00:00 2001 From: LilDosto Date: Wed, 28 Oct 2026 03:50:31 +0300 Subject: [PATCH] v2.1.0: Fluidity, responsiveness and zero-freeze performance optimization update --- .../MathApp/Controls/CombinatoricsControl.cs | 74 ++- .../Controls/DerivativeCalculatorControl.cs | 163 +++--- .../MathApp/Controls/GraphPlotterControl.cs | 47 +- .../Controls/MatrixCalculatorControl.cs | 472 ++++++++++-------- .../Controls/MultivariableTaylorControl.cs | 36 +- MathApp/MathApp/Controls/RootFinderControl.cs | 97 ++-- .../MathApp/Controls/SystemSolverControl.cs | 71 ++- .../MathApp/Controls/TaylorSeriesControl.cs | 58 ++- MathApp/MathApp/MainForm.cs | 55 +- .../MathApp.Tests/MathApp.Tests.csproj | 2 +- MathApp/MathApp/MathApp.csproj | 2 +- MathApp/MathApp/ThemeHelper.cs | 16 + 12 files changed, 674 insertions(+), 419 deletions(-) diff --git a/MathApp/MathApp/Controls/CombinatoricsControl.cs b/MathApp/MathApp/Controls/CombinatoricsControl.cs index 2d44af0..52c7e87 100644 --- a/MathApp/MathApp/Controls/CombinatoricsControl.cs +++ b/MathApp/MathApp/Controls/CombinatoricsControl.cs @@ -2,6 +2,7 @@ using System; using System.Drawing; using System.Globalization; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; using DotNetMatrix; @@ -80,36 +81,45 @@ namespace MathApp.Controls } } - private void BtnPascal_Click(object sender, EventArgs e) + private async void BtnPascal_Click(object sender, EventArgs e) { + Cursor = Cursors.WaitCursor; try { int n = (int)numN.Value; - StringBuilder sb = new StringBuilder(); - sb.AppendLine($"=== PASCAL UCGENI & BINOM KATSAYILARI (Derece n = {n}) ==="); - sb.AppendLine($"(a + b)^{n} açılımının katsayıları:"); - sb.AppendLine(); - - for (int row = 0; row <= Math.Min(n, 25); row++) + string result = await Task.Run(() => { - sb.Append($"n = {row,2} | "); - for (int k = 0; k <= row; k++) - { - decimal c = NumericalMethods.Combination(row, k); - sb.Append(c.ToString("N0") + (k < row ? ", " : "")); - } + StringBuilder sb = new StringBuilder(); + sb.AppendLine($"=== PASCAL UCGENI & BINOM KATSAYILARI (Derece n = {n}) ==="); + sb.AppendLine($"(a + b)^{n} açılımının katsayıları:"); sb.AppendLine(); - } - txtOutput.Text = sb.ToString(); + for (int row = 0; row <= Math.Min(n, 25); row++) + { + sb.Append($"n = {row,2} | "); + for (int k = 0; k <= row; k++) + { + decimal c = NumericalMethods.Combination(row, k); + sb.Append(c.ToString("N0") + (k < row ? ", " : "")); + } + sb.AppendLine(); + } + return sb.ToString(); + }); + + txtOutput.Text = result; } catch (Exception ex) { txtOutput.Text = "Hata: " + ex.Message; } + finally + { + Cursor = Cursors.Default; + } } - private void BtnGenStrings_Click(object sender, EventArgs e) + private async void BtnGenStrings_Click(object sender, EventArgs e) { try { @@ -136,23 +146,35 @@ namespace MathApp.Controls if (dr != DialogResult.Yes) return; } - string generated = NumericalMethods.GenerateCombinations(alphabet, prefix, length); + Cursor = Cursors.WaitCursor; + btnGenStrings.Enabled = false; - StringBuilder sb = new StringBuilder(); - sb.AppendLine("=== KARAKTER KOMBINASYON URETECI ==="); - sb.AppendLine($"Alfabe : '{alphabet}' (Uzunluk: {alphabet.Length})"); - sb.AppendLine($"Önek (Prefix) : '{prefix}'"); - sb.AppendLine($"Dizilim Boyutu: {length}"); - sb.AppendLine($"Toplam Sonuç : {totalCount:N0} adet"); - sb.AppendLine(new string('-', 45)); - sb.Append(generated); + string result = await Task.Run(() => + { + string generated = NumericalMethods.GenerateCombinations(alphabet, prefix, length); - txtOutput.Text = sb.ToString(); + StringBuilder sb = new StringBuilder(); + sb.AppendLine("=== KARAKTER KOMBINASYON URETECI ==="); + sb.AppendLine($"Alfabe : '{alphabet}' (Uzunluk: {alphabet.Length})"); + sb.AppendLine($"Önek (Prefix) : '{prefix}'"); + sb.AppendLine($"Dizilim Boyutu: {length}"); + sb.AppendLine($"Toplam Sonuç : {totalCount:N0} adet"); + sb.AppendLine(new string('-', 45)); + sb.Append(generated); + return sb.ToString(); + }); + + txtOutput.Text = result; } catch (Exception ex) { txtOutput.Text = "Kombinasyon Üretim Hatası: " + ex.Message; } + finally + { + btnGenStrings.Enabled = true; + Cursor = Cursors.Default; + } } private void BtnPolarConvert_Click(object sender, EventArgs e) diff --git a/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs b/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs index 5c7736c..6797a00 100644 --- a/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs +++ b/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs @@ -4,6 +4,7 @@ using System.Drawing; using System.Globalization; using System.Linq; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; namespace MathApp.Controls @@ -92,8 +93,13 @@ namespace MathApp.Controls throw new ArgumentException($"'{field}' için geçerli bir sayı giriniz."); } - private void BtnCalcSingle_Click(object sender, EventArgs e) + private async void BtnCalcSingle_Click(object sender, EventArgs e) { + string origBtnText = btnCalcSingle.Text; + btnCalcSingle.Enabled = false; + btnCalcSingle.Text = "⏳ Hesaplanıyor..."; + Cursor = Cursors.WaitCursor; + try { string eq = txtSingleFn.Text.Trim(); @@ -105,49 +111,65 @@ namespace MathApp.Controls int deg = (int)numSingleDegree.Value; int acc = (cmbAccuracy.SelectedIndex + 1) * 2; // 2, 4, 6 - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - try + string resultText = await Task.Run(() => { - decimal fVal = NumericalMethods.Method_EvaluateFunction(eq, v, pt); - decimal centralMat = NumericalMethods.Method_NumericalDifferentiation(eq, deg, v, pt, acc, h); - decimal forwardBin = NumericalMethods.Method_ForwardBinomialDerivative(eq, deg, v, pt, h); - decimal backwardDiff = NumericalMethods.Method_BackwardDifferenceDerivative(eq, deg, v, pt, h); - - StringBuilder sb = new StringBuilder(); - sb.AppendLine($"=== TEK DEĞİŞKENLİ NÜMERİK TÜREV ANALİZİ ({deg}. Derece) ==="); - sb.AppendLine($" Fonksiyon : f({v}) = {eq}"); - sb.AppendLine($" Değerlendirme : {v}₀ = {pt} => f({pt}) = {Math.Round(fVal, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine($" Adım Boyutu (h) : {h} | Hassasiyet: O(h^{acc})"); - sb.AppendLine(); - sb.AppendLine("--- Farklı Nümerik Yöntemlerin Karşılaştırması ---"); - sb.AppendLine($" 1) Merkezi Sonlu Farklar Matrisi (Method_NumericalDifferentiation) : {Math.Round(centralMat, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine($" 2) İleri Binom Sonlu Farklar (Method_Derivative) : {Math.Round(forwardBin, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine($" 3) Geri Sonlu Farklar Formülü (Method_BackwardDerivative) : {Math.Round(backwardDiff, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine(); - sb.AppendLine("--- 1'den 4. Dereceye Kadar Tüm Türev Özeti ---"); - for (int k = 1; k <= 4; k++) + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try { - decimal step = k >= 3 ? Math.Max(h, 0.005m) : h; - decimal dk = NumericalMethods.Method_NumericalDifferentiation(eq, k, v, pt, acc, step); - sb.AppendLine($" • f^({k})({pt}) = {Math.Round(dk, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); - } + decimal fVal = NumericalMethods.Method_EvaluateFunction(eq, v, pt); + decimal centralMat = NumericalMethods.Method_NumericalDifferentiation(eq, deg, v, pt, acc, h); + decimal forwardBin = NumericalMethods.Method_ForwardBinomialDerivative(eq, deg, v, pt, h); + decimal backwardDiff = NumericalMethods.Method_BackwardDifferenceDerivative(eq, deg, v, pt, h); - txtResult.Text = sb.ToString(); - } - finally - { - Function.UseRadians = prevRad; - } + StringBuilder sb = new StringBuilder(); + sb.AppendLine($"=== TEK DEĞİŞKENLİ NÜMERİK TÜREV ANALİZİ ({deg}. Derece) ==="); + sb.AppendLine($" Fonksiyon : f({v}) = {eq}"); + sb.AppendLine($" Değerlendirme : {v}₀ = {pt} => f({pt}) = {Math.Round(fVal, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine($" Adım Boyutu (h) : {h} | Hassasiyet: O(h^{acc})"); + sb.AppendLine(); + sb.AppendLine("--- Farklı Nümerik Yöntemlerin Karşılaştırması ---"); + sb.AppendLine($" 1) Merkezi Sonlu Farklar Matrisi (Method_NumericalDifferentiation) : {Math.Round(centralMat, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine($" 2) İleri Binom Sonlu Farklar (Method_Derivative) : {Math.Round(forwardBin, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine($" 3) Geri Sonlu Farklar Formülü (Method_BackwardDerivative) : {Math.Round(backwardDiff, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine(); + sb.AppendLine("--- 1'den 4. Dereceye Kadar Tüm Türev Özeti ---"); + for (int k = 1; k <= 4; k++) + { + decimal step = k >= 3 ? Math.Max(h, 0.005m) : h; + decimal dk = NumericalMethods.Method_NumericalDifferentiation(eq, k, v, pt, acc, step); + sb.AppendLine($" • f^({k})({pt}) = {Math.Round(dk, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); + } + + return sb.ToString(); + } + finally + { + Function.UseRadians = prevRad; + } + }); + + txtResult.Text = resultText; } catch (Exception ex) { txtResult.Text = "❌ Hata: " + ex.Message; } + finally + { + btnCalcSingle.Enabled = true; + btnCalcSingle.Text = origBtnText; + Cursor = Cursors.Default; + } } - private void BtnCalcPartial_Click(object sender, EventArgs e) + private async void BtnCalcPartial_Click(object sender, EventArgs e) { + string origBtnText = btnCalcPartial.Text; + btnCalcPartial.Enabled = false; + btnCalcPartial.Text = "⏳ Hesaplanıyor..."; + Cursor = Cursors.WaitCursor; + try { string eq = txtPartialFn.Text.Trim(); @@ -171,46 +193,57 @@ namespace MathApp.Controls return; } - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - try + string resultText = await Task.Run(() => { - decimal fVal = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, pts); - decimal partialMat = NumericalMethods.Method_NumericalPartialDifferentiation(eq, deg, targetVar, pts, acc, h); - decimal partialBin = NumericalMethods.Method_ForwardBinomialPartialDerivative(eq, deg, targetVar, pts, h); - - StringBuilder sb = new StringBuilder(); - string ptStr = string.Join(", ", pts.Select(kv => $"{kv.Key}={kv.Value}")); - sb.AppendLine($"=== KISMİ TÜREV VE GRADYAN ANALİZİ (∂^{deg}f / ∂{targetVar}^{deg}) ==="); - sb.AppendLine($" Fonksiyon : f({string.Join(",", pts.Keys)}) = {eq}"); - sb.AppendLine($" Nokta : ({ptStr}) => f = {Math.Round(fVal, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine(); - sb.AppendLine($"--- '{targetVar}' Değişkenine Göre {deg}. Derece Kısmi Türev ---"); - sb.AppendLine($" • Merkezi Matris Yöntemi (Method_NumericalPartialDifferentiation) : {Math.Round(partialMat, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine($" • İleri Binom Yöntemi (Method_PartialDerivative) : {Math.Round(partialBin, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); - sb.AppendLine(); - sb.AppendLine("--- Noktadaki Gradyan Vektörü (∇f) ---"); - List gradParts = new List(); - foreach (string vName in pts.Keys) + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try { - decimal df = NumericalMethods.Method_NumericalPartialDifferentiation(eq, 1, vName, pts, acc, h); - decimal rDf = Math.Round(df, 6); - gradParts.Add(rDf.ToString("0.######", CultureInfo.InvariantCulture)); - sb.AppendLine($" • ∂f / ∂{vName} = {rDf.ToString("0.######", CultureInfo.InvariantCulture)}"); - } - sb.AppendLine($" ∇f({ptStr}) = [ {string.Join(", ", gradParts)} ]"); + decimal fVal = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, pts); + decimal partialMat = NumericalMethods.Method_NumericalPartialDifferentiation(eq, deg, targetVar, pts, acc, h); + decimal partialBin = NumericalMethods.Method_ForwardBinomialPartialDerivative(eq, deg, targetVar, pts, h); - txtResult.Text = sb.ToString(); - } - finally - { - Function.UseRadians = prevRad; - } + StringBuilder sb = new StringBuilder(); + string ptStr = string.Join(", ", pts.Select(kv => $"{kv.Key}={kv.Value}")); + sb.AppendLine($"=== KISMİ TÜREV VE GRADYAN ANALİZİ (∂^{deg}f / ∂{targetVar}^{deg}) ==="); + sb.AppendLine($" Fonksiyon : f({string.Join(",", pts.Keys)}) = {eq}"); + sb.AppendLine($" Nokta : ({ptStr}) => f = {Math.Round(fVal, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine(); + sb.AppendLine($"--- '{targetVar}' Değişkenine Göre {deg}. Derece Kısmi Türev ---"); + sb.AppendLine($" • Merkezi Matris Yöntemi (Method_NumericalPartialDifferentiation) : {Math.Round(partialMat, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine($" • İleri Binom Yöntemi (Method_PartialDerivative) : {Math.Round(partialBin, 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + sb.AppendLine(); + sb.AppendLine("--- Noktadaki Gradyan Vektörü (∇f) ---"); + List gradParts = new List(); + foreach (string vName in pts.Keys) + { + decimal df = NumericalMethods.Method_NumericalPartialDifferentiation(eq, 1, vName, pts, acc, h); + decimal rDf = Math.Round(df, 6); + gradParts.Add(rDf.ToString("0.######", CultureInfo.InvariantCulture)); + sb.AppendLine($" • ∂f / ∂{vName} = {rDf.ToString("0.######", CultureInfo.InvariantCulture)}"); + } + sb.AppendLine($" ∇f({ptStr}) = [ {string.Join(", ", gradParts)} ]"); + + return sb.ToString(); + } + finally + { + Function.UseRadians = prevRad; + } + }); + + txtResult.Text = resultText; } catch (Exception ex) { txtResult.Text = "❌ Hata: " + ex.Message; } + finally + { + btnCalcPartial.Enabled = true; + btnCalcPartial.Text = origBtnText; + Cursor = Cursors.Default; + } } } } diff --git a/MathApp/MathApp/Controls/GraphPlotterControl.cs b/MathApp/MathApp/Controls/GraphPlotterControl.cs index 81662f5..d636d52 100644 --- a/MathApp/MathApp/Controls/GraphPlotterControl.cs +++ b/MathApp/MathApp/Controls/GraphPlotterControl.cs @@ -24,11 +24,24 @@ namespace MathApp.Controls private bool didMoveMouse = false; private Point lastMousePos; private Point? hoverMousePos = null; + private Point lastHoverRecorded = new Point(-999, -999); + private Timer resampleDebounceTimer; public GraphPlotterControl() { InitializeComponent(); + resampleDebounceTimer = new Timer { Interval = 50 }; + resampleDebounceTimer.Tick += (s, e) => + { + resampleDebounceTimer.Stop(); + if (!isDragging && compiledFn != null) + { + GeneratePoints(false, isDraft: false); + pnlCanvas.Invalidate(); + } + }; + // Enable DoubleBuffering on pnlCanvas to prevent flickering during pan/zoom typeof(Panel).InvokeMember( "DoubleBuffered", @@ -120,12 +133,14 @@ namespace MathApp.Controls return def; } - private void GeneratePoints(bool autoFitY) + private void GeneratePoints(bool autoFitY, bool isDraft = false) { segments.Clear(); if (compiledFn == null) return; - int sampleCount = Math.Max(600, pnlCanvas.Width * 2); + int sampleCount = isDraft + ? Math.Min(220, Math.Max(120, pnlCanvas.Width / 3)) + : Math.Max(600, pnlCanvas.Width * 2); float step = (rangeMaxX - rangeMinX) / sampleCount; if (step <= 0) return; @@ -229,7 +244,10 @@ namespace MathApp.Controls txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture); txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); - GeneratePoints(false); + // Fast preview during continuous wheel spin, debounce high-res + GeneratePoints(false, isDraft: true); + resampleDebounceTimer.Stop(); + resampleDebounceTimer.Start(); pnlCanvas.Invalidate(); } @@ -247,10 +265,9 @@ namespace MathApp.Controls private void PnlCanvas_MouseMove(object sender, MouseEventArgs e) { - hoverMousePos = e.Location; - if (isDragging) { + hoverMousePos = e.Location; int dx = e.X - lastMousePos.X; int dy = e.Y - lastMousePos.Y; @@ -277,10 +294,22 @@ namespace MathApp.Controls txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); lastMousePos = e.Location; - GeneratePoints(false); + // Fluid high-FPS drag preview + GeneratePoints(false, isDraft: true); + resampleDebounceTimer.Stop(); + resampleDebounceTimer.Start(); + pnlCanvas.Invalidate(); + } + else + { + // Throttle hover redraws: only repaint when moved at least 2 pixels + if (Math.Abs(e.X - lastHoverRecorded.X) >= 2 || Math.Abs(e.Y - lastHoverRecorded.Y) >= 2) + { + lastHoverRecorded = e.Location; + hoverMousePos = e.Location; + pnlCanvas.Invalidate(); + } } - - pnlCanvas.Invalidate(); } private void PnlCanvas_MouseUp(object sender, MouseEventArgs e) @@ -315,6 +344,8 @@ namespace MathApp.Controls } isDragging = false; + resampleDebounceTimer.Stop(); + GeneratePoints(false, isDraft: false); Cursor = Cursors.Cross; pnlCanvas.Invalidate(); } diff --git a/MathApp/MathApp/Controls/MatrixCalculatorControl.cs b/MathApp/MathApp/Controls/MatrixCalculatorControl.cs index 39df583..8c66e2f 100644 --- a/MathApp/MathApp/Controls/MatrixCalculatorControl.cs +++ b/MathApp/MathApp/Controls/MatrixCalculatorControl.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; using DotNetMatrix; @@ -228,263 +229,300 @@ namespace MathApp.Controls return sb.ToString(); } - private void RunBinaryOperation(string op) + private async void RunBinaryOperation(string op) { + Cursor = Cursors.WaitCursor; try { GeneralMatrix A = ReadMatrix(gridCellsA, rowsA, colsA, "A"); - StringBuilder sb = new StringBuilder(); + string sRaw = txtScalar.Text.Trim().Replace(',', '.'); + GeneralMatrix B = null; + decimal k = 0m; if (op == "SCALAR") { - string sRaw = txtScalar.Text.Trim().Replace(',', '.'); - if (!decimal.TryParse(sRaw, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal k)) + if (!decimal.TryParse(sRaw, NumberStyles.Any, CultureInfo.InvariantCulture, out k)) { txtResult.Text = "❌ Geçerli bir skaler çarpan (k) giriniz."; return; } - GeneralMatrix res = A.Multiply(k); - lastResultMatrix = res; - sb.AppendLine($"=== SKALER ÇARPIM (k · A, k = {k}) ==="); - sb.Append(FormatMatrix(res)); - txtResult.Text = sb.ToString(); - return; + } + else + { + B = ReadMatrix(gridCellsB, rowsB, colsB, "B"); } - GeneralMatrix B = ReadMatrix(gridCellsB, rowsB, colsB, "B"); + var (resultMatrix, outputText) = await Task.Run(() => + { + StringBuilder sb = new StringBuilder(); + GeneralMatrix res = null; - if (op == "ADD") - { - lastResultMatrix = A + B; - sb.AppendLine("=== MATRİS TOPLAMI (A + B) ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } - else if (op == "SUB") - { - lastResultMatrix = A - B; - sb.AppendLine("=== MATRİS FARKI (A - B) ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } - else if (op == "MUL") - { - lastResultMatrix = A * B; - sb.AppendLine($"=== MATRİS ÇARPIMI (A × B) [{rowsA}x{colsA}] · [{rowsB}x{colsB}] ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } - else if (op == "ELEM_MUL") - { - lastResultMatrix = A.ArrayMultiply(B); - sb.AppendLine("=== ELEMAN BAZLI (HADAMARD) ÇARPIM (A .* B) ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } - else if (op == "ELEM_DIV") - { - lastResultMatrix = A.ArrayRightDivide(B); - sb.AppendLine("=== ELEMAN BAZLI BÖLME (A ./ B) ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } - else if (op == "SOLVE") - { - lastResultMatrix = A.Solve(B); - sb.AppendLine("=== MATRİS DENKLEMİ ÇÖZÜMÜ (A · X = B => X) ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } - else if (op == "SOLVE_TRANS") - { - lastResultMatrix = A.SolveTranspose(B); - sb.AppendLine("=== TRANSPOZ MATRİS DENKLEMİ ÇÖZÜMÜ (Aᵀ · Xᵀ = Bᵀ) ==="); - sb.Append(FormatMatrix(lastResultMatrix)); - } + if (op == "SCALAR") + { + res = A.Multiply(k); + sb.AppendLine($"=== SKALER ÇARPIM (k · A, k = {k}) ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "ADD") + { + res = A + B; + sb.AppendLine("=== MATRİS TOPLAMI (A + B) ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "SUB") + { + res = A - B; + sb.AppendLine("=== MATRİS FARKI (A - B) ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "MUL") + { + res = A * B; + sb.AppendLine($"=== MATRİS ÇARPIMI (A × B) [{rowsA}x{colsA}] · [{rowsB}x{colsB}] ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "ELEM_MUL") + { + res = A.ArrayMultiply(B); + sb.AppendLine("=== ELEMAN BAZLI (HADAMARD) ÇARPIM (A .* B) ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "ELEM_DIV") + { + res = A.ArrayRightDivide(B); + sb.AppendLine("=== ELEMAN BAZLI BÖLME (A ./ B) ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "SOLVE") + { + res = A.Solve(B); + sb.AppendLine("=== MATRİS DENKLEMİ ÇÖZÜMÜ (A · X = B => X) ==="); + sb.Append(FormatMatrix(res)); + } + else if (op == "SOLVE_TRANS") + { + res = A.SolveTranspose(B); + sb.AppendLine("=== TRANSPOZ MATRİS DENKLEMİ ÇÖZÜMÜ (Aᵀ · Xᵀ = Bᵀ) ==="); + sb.Append(FormatMatrix(res)); + } - txtResult.Text = sb.ToString(); + return (res, sb.ToString()); + }); + + if (resultMatrix != null) + { + lastResultMatrix = resultMatrix; + } + txtResult.Text = outputText; } catch (Exception ex) { txtResult.Text = "❌ İşlem Hatası: " + ex.Message; } + finally + { + Cursor = Cursors.Default; + } } - private void RunUnaryOperation(string op) + private async void RunUnaryOperation(string op) { + Cursor = Cursors.WaitCursor; try { GeneralMatrix A = ReadMatrix(gridCellsA, rowsA, colsA, "A"); - StringBuilder sb = new StringBuilder(); - if (op == "ALL") + if (op == "LU" && rowsA < colsA) { - sb.AppendLine($"=== A MATRİSİ TAM ANALİZİ ({rowsA}x{colsA}) ==="); - sb.AppendLine($" • İz (Trace) : {Math.Round(A.Trace(), 6)}"); - sb.AppendLine($" • 1-Normu (Norm1) : {Math.Round(A.Norm1(), 5)}"); - sb.AppendLine($" • Sonsuz-Normu (NormInf) : {Math.Round(A.NormInf(), 5)}"); - sb.AppendLine($" • Frobenius Normu (NormF) : {Math.Round(A.NormF(), 5)}"); + txtResult.Text = "⚠️ LU Ayrışımı için satır sayısı sütun sayısına eşit veya büyük (m >= n) olmalıdır."; + return; + } + if (op == "QR" && rowsA < colsA) + { + txtResult.Text = "⚠️ QR Ayrışımı için satır sayısı sütun sayısına eşit veya büyük (m >= n) olmalıdır."; + return; + } + if (op == "CHOLESKY" && rowsA != colsA) + { + txtResult.Text = "⚠️ Cholesky Ayrışımı yalnızca kare matrisler için uygulanabilir."; + return; + } + if (op == "EIGEN" && rowsA != colsA) + { + txtResult.Text = "⚠️ Özdeğer & Özvektör analizi yalnızca kare (N x N) matrisler için yapılabilir."; + return; + } + if (op == "INVERSE" && rowsA != colsA) + { + txtResult.Text = "⚠️ Ters matris ve determinant yalnızca kare (N x N) matrisler için hesaplanabilir."; + return; + } - try + var (resultMatrix, outputText) = await Task.Run(() => + { + StringBuilder sb = new StringBuilder(); + GeneralMatrix res = null; + + if (op == "ALL") { - SingularValueDecomposition svd = A.SVD(); - sb.AppendLine($" • 2-Normu (Spektral Norm) : {Math.Round(svd.Norm2(), 5)}"); - sb.AppendLine($" • Matris Rankı (Rank) : {svd.Rank()}"); - sb.AppendLine($" • Kondisyon Sayısı (Cond) : {Math.Round(svd.Condition(), 5)}"); - } - catch { } + sb.AppendLine($"=== A MATRİSİ TAM ANALİZİ ({rowsA}x{colsA}) ==="); + sb.AppendLine($" • İz (Trace) : {Math.Round(A.Trace(), 6)}"); + sb.AppendLine($" • 1-Normu (Norm1) : {Math.Round(A.Norm1(), 5)}"); + sb.AppendLine($" • Sonsuz-Normu (NormInf) : {Math.Round(A.NormInf(), 5)}"); + sb.AppendLine($" • Frobenius Normu (NormF) : {Math.Round(A.NormF(), 5)}"); - if (rowsA == colsA) - { - decimal det = A.Determinant(); - sb.AppendLine($" • Determinant det(A) : {Math.Round(det, 6)}"); - } - - sb.AppendLine(); - sb.AppendLine("--- Transpoz (Aᵀ) ---"); - sb.Append(FormatMatrix(A.Transpose())); - - sb.AppendLine(); - sb.AppendLine("--- Negatif Matris (-A / UnaryMinus) ---"); - sb.Append(FormatMatrix(A.UnaryMinus())); - - if (rowsA == colsA) - { try { - sb.AppendLine(); - sb.AppendLine("--- Ters Matris (A⁻¹) ---"); - sb.Append(FormatMatrix(A.Inverse())); + SingularValueDecomposition svd = A.SVD(); + sb.AppendLine($" • 2-Normu (Spektral Norm) : {Math.Round(svd.Norm2(), 5)}"); + sb.AppendLine($" • Matris Rankı (Rank) : {svd.Rank()}"); + sb.AppendLine($" • Kondisyon Sayısı (Cond) : {Math.Round(svd.Condition(), 5)}"); } - catch - { - sb.AppendLine(" (Matris tekil [singular] olduğu için tersi yoktur.)"); - } - } - } - else if (op == "LU") - { - if (rowsA < colsA) - { - txtResult.Text = "⚠️ LU Ayrışımı için satır sayısı sütun sayısına eşit veya büyük (m >= n) olmalıdır."; - return; - } - LUDecomposition lu = A.LUD(); - sb.AppendLine("=== LU AYRIŞIMI (P·A = L·U) ==="); - sb.AppendLine($"Tekil Olmama Durumu (Non-Singular): {(lu.IsNonSingular ? "Evet (Tersinir)" : "Hayır (Tekil)")}"); - if (rowsA == colsA) - sb.AppendLine($"Determinant: {Math.Round(lu.Determinant(), 6)}"); - sb.AppendLine($"Pivot Vektörü: [ {string.Join(", ", lu.Pivot)} ]"); - sb.AppendLine(); - sb.AppendLine("--- Alt Üçgensel Matris (L) ---"); - sb.Append(FormatMatrix(lu.L)); - sb.AppendLine(); - sb.AppendLine("--- Üst Üçgensel Matris (U) ---"); - sb.Append(FormatMatrix(lu.U)); - } - else if (op == "QR") - { - if (rowsA < colsA) - { - txtResult.Text = "⚠️ QR Ayrışımı için satır sayısı sütun sayısına eşit veya büyük (m >= n) olmalıdır."; - return; - } - QRDecomposition qr = A.QRD(); - sb.AppendLine("=== QR AYRIŞIMI (A = Q·R) ==="); - sb.AppendLine($"Tam Rank (Full Rank): {(qr.FullRank ? "Evet" : "Hayır")}"); - sb.AppendLine(); - sb.AppendLine("--- Ortogonal Matris (Q) ---"); - sb.Append(FormatMatrix(qr.Q)); - sb.AppendLine(); - sb.AppendLine("--- Üst Üçgensel Matris (R) ---"); - sb.Append(FormatMatrix(qr.R)); - sb.AppendLine(); - sb.AppendLine("--- Householder Yansıma Vektörleri Matrisi (H) ---"); - sb.Append(FormatMatrix(qr.H)); - } - else if (op == "CHOLESKY") - { - if (rowsA != colsA) - { - txtResult.Text = "⚠️ Cholesky Ayrışımı yalnızca kare matrisler için uygulanabilir."; - return; - } - CholeskyDecomposition chol = A.chol(); - sb.AppendLine("=== CHOLESKY AYRIŞIMI (A = L·Lᵀ) ==="); - sb.AppendLine($"Simetrik Pozitif Tanımlı (SPD): {(chol.SPD ? "Evet ✓" : "Hayır ✕")}"); - if (!chol.SPD) - { - sb.AppendLine("⚠️ Uyarı: Bu matris simetrik pozitif tanımlı (SPD) değildir! 'Örnek: SPD Matrisi' butonuna tıklayarak test edebilirsiniz."); - } - sb.AppendLine(); - sb.AppendLine("--- Cholesky Alt Üçgensel Çarpanı (L) ---"); - sb.Append(FormatMatrix(chol.GetL())); - } - else if (op == "SVD") - { - SingularValueDecomposition svd = A.SVD(); - sb.AppendLine("=== TEKİL DEĞER AYRIŞIMI (SVD: A = U·S·Vᵀ) ==="); - sb.AppendLine($"Matris Rankı (Rank) : {svd.Rank()}"); - sb.AppendLine($"2-Normu (Norm2) : {Math.Round(svd.Norm2(), 6)}"); - sb.AppendLine($"Kondisyon Sayısı (Cond) : {Math.Round(svd.Condition(), 6)}"); - sb.AppendLine(); - sb.AppendLine("--- Tekil Değerler Matrisi (S) ---"); - sb.Append(FormatMatrix(svd.S)); - sb.AppendLine(); - sb.AppendLine("--- Sol Tekil Vektörler (U) ---"); - sb.Append(FormatMatrix(svd.GetU())); - sb.AppendLine(); - sb.AppendLine("--- Sağ Tekil Vektörler (V) ---"); - sb.Append(FormatMatrix(svd.GetV())); - } - else if (op == "EIGEN") - { - if (rowsA != colsA) - { - txtResult.Text = "⚠️ Özdeğer & Özvektör analizi yalnızca kare (N x N) matrisler için yapılabilir."; - return; - } - EigenvalueDecomposition eig = A.Eigen(); - sb.AppendLine("=== ÖZDEĞER VE ÖZVEKTÖR ANALİZİ (A·v = λ·v) ==="); - decimal[] realEigs = eig.RealEigenvalues; - decimal[] imagEigs = eig.ImagEigenvalues; - for (int i = 0; i < realEigs.Length; i++) - { - decimal re = Math.Round(realEigs[i], 6); - decimal im = Math.Round(imagEigs[i], 6); - string imStr = DecimalMath.Abs(im) > 0.00001m ? $" {(im >= 0 ? "+" : "-")} {DecimalMath.Abs(im)}i" : ""; - sb.AppendLine($" λ_{i + 1} = {re.ToString("0.######", CultureInfo.InvariantCulture)}{imStr}"); - } - sb.AppendLine(); - sb.AppendLine("--- Blok Diyagonal Özdeğer Matrisi (D) ---"); - sb.Append(FormatMatrix(eig.D)); - sb.AppendLine(); - sb.AppendLine("--- Özvektörler Matrisi (V) ---"); - sb.Append(FormatMatrix(eig.GetV())); - } - else if (op == "INVERSE") - { - if (rowsA != colsA) - { - txtResult.Text = "⚠️ Ters matris ve determinant yalnızca kare (N x N) matrisler için hesaplanabilir."; - return; - } - decimal det = A.Determinant(); - sb.AppendLine($"=== TERS MATRİS (A⁻¹) & DETERMİNANT ==="); - sb.AppendLine($"Determinant det(A) = {Math.Round(det, 6)}"); - sb.AppendLine(); - if (DecimalMath.Abs(det) <= 1e-12m) - { - sb.AppendLine("❌ Matrisin determinantı 0 olduğu için matris tekildir (Singular), tersi alınamaz."); - } - else - { - sb.AppendLine("--- Ters Matris (A⁻¹) ---"); - lastResultMatrix = A.Inverse(); - sb.Append(FormatMatrix(lastResultMatrix)); - } - } + catch { } - txtResult.Text = sb.ToString(); + if (rowsA == colsA) + { + decimal det = A.Determinant(); + sb.AppendLine($" • Determinant det(A) : {Math.Round(det, 6)}"); + } + + sb.AppendLine(); + sb.AppendLine("--- Transpoz (Aᵀ) ---"); + sb.Append(FormatMatrix(A.Transpose())); + + sb.AppendLine(); + sb.AppendLine("--- Negatif Matris (-A / UnaryMinus) ---"); + sb.Append(FormatMatrix(A.UnaryMinus())); + + if (rowsA == colsA) + { + try + { + sb.AppendLine(); + sb.AppendLine("--- Ters Matris (A⁻¹) ---"); + sb.Append(FormatMatrix(A.Inverse())); + } + catch + { + sb.AppendLine(" (Matris tekil [singular] olduğu için tersi yoktur.)"); + } + } + } + else if (op == "LU") + { + LUDecomposition lu = A.LUD(); + sb.AppendLine("=== LU AYRIŞIMI (P·A = L·U) ==="); + sb.AppendLine($"Tekil Olmama Durumu (Non-Singular): {(lu.IsNonSingular ? "Evet (Tersinir)" : "Hayır (Tekil)")}"); + if (rowsA == colsA) + sb.AppendLine($"Determinant: {Math.Round(lu.Determinant(), 6)}"); + sb.AppendLine($"Pivot Vektörü: [ {string.Join(", ", lu.Pivot)} ]"); + sb.AppendLine(); + sb.AppendLine("--- Alt Üçgensel Matris (L) ---"); + sb.Append(FormatMatrix(lu.L)); + sb.AppendLine(); + sb.AppendLine("--- Üst Üçgensel Matris (U) ---"); + sb.Append(FormatMatrix(lu.U)); + } + else if (op == "QR") + { + QRDecomposition qr = A.QRD(); + sb.AppendLine("=== QR AYRIŞIMI (A = Q·R) ==="); + sb.AppendLine($"Tam Rank (Full Rank): {(qr.FullRank ? "Evet" : "Hayır")}"); + sb.AppendLine(); + sb.AppendLine("--- Ortogonal Matris (Q) ---"); + sb.Append(FormatMatrix(qr.Q)); + sb.AppendLine(); + sb.AppendLine("--- Üst Üçgensel Matris (R) ---"); + sb.Append(FormatMatrix(qr.R)); + sb.AppendLine(); + sb.AppendLine("--- Householder Yansıma Vektörleri Matrisi (H) ---"); + sb.Append(FormatMatrix(qr.H)); + } + else if (op == "CHOLESKY") + { + CholeskyDecomposition chol = A.chol(); + sb.AppendLine("=== CHOLESKY AYRIŞIMI (A = L·Lᵀ) ==="); + sb.AppendLine($"Simetrik Pozitif Tanımlı (SPD): {(chol.SPD ? "Evet ✓" : "Hayır ✕")}"); + if (!chol.SPD) + { + sb.AppendLine("⚠️ Uyarı: Bu matris simetrik pozitif tanımlı (SPD) değildir! 'Örnek: SPD Matrisi' butonuna tıklayarak test edebilirsiniz."); + } + sb.AppendLine(); + sb.AppendLine("--- Cholesky Alt Üçgensel Çarpanı (L) ---"); + sb.Append(FormatMatrix(chol.GetL())); + } + else if (op == "SVD") + { + SingularValueDecomposition svd = A.SVD(); + sb.AppendLine("=== TEKİL DEĞER AYRIŞIMI (SVD: A = U·S·Vᵀ) ==="); + sb.AppendLine($"Matris Rankı (Rank) : {svd.Rank()}"); + sb.AppendLine($"2-Normu (Norm2) : {Math.Round(svd.Norm2(), 6)}"); + sb.AppendLine($"Kondisyon Sayısı (Cond) : {Math.Round(svd.Condition(), 6)}"); + sb.AppendLine(); + sb.AppendLine("--- Tekil Değerler Matrisi (S) ---"); + sb.Append(FormatMatrix(svd.S)); + sb.AppendLine(); + sb.AppendLine("--- Sol Tekil Vektörler (U) ---"); + sb.Append(FormatMatrix(svd.GetU())); + sb.AppendLine(); + sb.AppendLine("--- Sağ Tekil Vektörler (V) ---"); + sb.Append(FormatMatrix(svd.GetV())); + } + else if (op == "EIGEN") + { + EigenvalueDecomposition eig = A.Eigen(); + sb.AppendLine("=== ÖZDEĞER VE ÖZVEKTÖR ANALİZİ (A·v = λ·v) ==="); + decimal[] realEigs = eig.RealEigenvalues; + decimal[] imagEigs = eig.ImagEigenvalues; + for (int i = 0; i < realEigs.Length; i++) + { + decimal re = Math.Round(realEigs[i], 6); + decimal im = Math.Round(imagEigs[i], 6); + string imStr = DecimalMath.Abs(im) > 0.00001m ? $" {(im >= 0 ? "+" : "-")} {DecimalMath.Abs(im)}i" : ""; + sb.AppendLine($" λ_{i + 1} = {re.ToString("0.######", CultureInfo.InvariantCulture)}{imStr}"); + } + sb.AppendLine(); + sb.AppendLine("--- Blok Diyagonal Özdeğer Matrisi (D) ---"); + sb.Append(FormatMatrix(eig.D)); + sb.AppendLine(); + sb.AppendLine("--- Özvektörler Matrisi (V) ---"); + sb.Append(FormatMatrix(eig.GetV())); + } + else if (op == "INVERSE") + { + decimal det = A.Determinant(); + sb.AppendLine($"=== TERS MATRİS (A⁻¹) & DETERMİNANT ==="); + sb.AppendLine($"Determinant det(A) = {Math.Round(det, 6)}"); + sb.AppendLine(); + if (DecimalMath.Abs(det) <= 1e-12m) + { + sb.AppendLine("❌ Matrisin determinantı 0 olduğu için matris tekildir (Singular), tersi alınamaz."); + } + else + { + sb.AppendLine("--- Ters Matris (A⁻¹) ---"); + res = A.Inverse(); + sb.Append(FormatMatrix(res)); + } + } + + return (res, sb.ToString()); + }); + + if (resultMatrix != null) + { + lastResultMatrix = resultMatrix; + } + txtResult.Text = outputText; } catch (Exception ex) { txtResult.Text = "❌ Hesaplama Hatası: " + ex.Message; } + finally + { + Cursor = Cursors.Default; + } } } } diff --git a/MathApp/MathApp/Controls/MultivariableTaylorControl.cs b/MathApp/MathApp/Controls/MultivariableTaylorControl.cs index e20ac61..e2c4585 100644 --- a/MathApp/MathApp/Controls/MultivariableTaylorControl.cs +++ b/MathApp/MathApp/Controls/MultivariableTaylorControl.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; +using System.Threading.Tasks; using System.Windows.Forms; namespace MathApp.Controls @@ -74,8 +75,13 @@ namespace MathApp.Controls variableRows.Add(row); } - private void BtnCalculate_Click(object sender, EventArgs e) + private async void BtnCalculate_Click(object sender, EventArgs e) { + string origBtnText = btnCalculate.Text; + btnCalculate.Enabled = false; + btnCalculate.Text = "⏳ Hesaplanıyor..."; + Cursor = Cursors.WaitCursor; + try { string eq = txtEquation.Text.Trim(); @@ -114,17 +120,19 @@ namespace MathApp.Controls return; } - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - string result; - try + string result = await Task.Run(() => { - result = NumericalMethods.MethodMultiVar_TaylorSeries(eq, degree, points); - } - finally - { - Function.UseRadians = prevRad; - } + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + return NumericalMethods.MethodMultiVar_TaylorSeries(eq, degree, points); + } + finally + { + Function.UseRadians = prevRad; + } + }); string varsList = string.Join(", ", points.Keys); string centerList = string.Join(", ", points.Select(kv => $"{kv.Key}₀={kv.Value}")); @@ -139,6 +147,12 @@ namespace MathApp.Controls { txtResult.Text = "❌ Hata: " + ex.Message; } + finally + { + btnCalculate.Enabled = true; + btnCalculate.Text = origBtnText; + Cursor = Cursors.Default; + } } } diff --git a/MathApp/MathApp/Controls/RootFinderControl.cs b/MathApp/MathApp/Controls/RootFinderControl.cs index 53793d5..2294521 100644 --- a/MathApp/MathApp/Controls/RootFinderControl.cs +++ b/MathApp/MathApp/Controls/RootFinderControl.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; +using System.Threading.Tasks; using System.Windows.Forms; namespace MathApp.Controls @@ -100,8 +101,13 @@ namespace MathApp.Controls throw new ArgumentException($"'{fieldName}' alanı için geçerli bir sayı giriniz."); } - private void BtnFindRoot_Click(object sender, EventArgs e) + private async void BtnFindRoot_Click(object sender, EventArgs e) { + string origBtnText = btnFindRoot.Text; + btnFindRoot.Enabled = false; + btnFindRoot.Text = "⏳ Hesaplanıyor..."; + Cursor = Cursors.WaitCursor; + try { string eq = txtEquation.Text.Trim(); @@ -118,55 +124,62 @@ namespace MathApp.Controls iterCount = 50; int idx = cmbMethod.SelectedIndex; - List logs; + string initPtText = txtInitialPoint.Text; + string minXText = txtMinX.Text; + string maxXText = txtMaxX.Text; - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - try + var (logs, finalRoot) = await Task.Run(() => { - if (idx == 0) // Newton-Raphson + List stepLogs; + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try { - decimal initialP = ParseDecimal(txtInitialPoint.Text, "Başlangıç Noktası (x₀)"); - logs = NumericalMethods.Method_NewtonRaphson(eq, initialP, iterCount, variable); + if (idx == 0) // Newton-Raphson + { + decimal initialP = ParseDecimal(initPtText, "Başlangıç Noktası (x₀)"); + stepLogs = NumericalMethods.Method_NewtonRaphson(eq, initialP, iterCount, variable); + } + else if (idx == 1) // Bisection + { + decimal minX = ParseDecimal(minXText, "Alt Sınır (a)"); + decimal maxX = ParseDecimal(maxXText, "Üst Sınır (b)"); + stepLogs = NumericalMethods.Method_Bisection(eq, minX, maxX, iterCount, variable); + } + else if (idx == 2) // Secant + { + decimal minX = ParseDecimal(minXText, "Başlangıç 1 (x₀)"); + decimal maxX = ParseDecimal(maxXText, "Başlangıç 2 (x₁)"); + stepLogs = NumericalMethods.Method_Secant(eq, minX, maxX, iterCount, variable); + } + else // Regula Falsi + { + decimal minX = ParseDecimal(minXText, "Alt Sınır (a)"); + decimal maxX = ParseDecimal(maxXText, "Üst Sınır (b)"); + stepLogs = NumericalMethods.Method_RegulaFalsi(eq, minX, maxX, iterCount, variable); + } } - else if (idx == 1) // Bisection + finally { - decimal minX = ParseDecimal(txtMinX.Text, "Alt Sınır (a)"); - decimal maxX = ParseDecimal(txtMaxX.Text, "Üst Sınır (b)"); - logs = NumericalMethods.Method_Bisection(eq, minX, maxX, iterCount, variable); + Function.UseRadians = prevRad; } - else if (idx == 2) // Secant + + string rootFound = ""; + for (int i = stepLogs.Count - 1; i >= 0; i--) { - decimal minX = ParseDecimal(txtMinX.Text, "Başlangıç 1 (x₀)"); - decimal maxX = ParseDecimal(txtMaxX.Text, "Başlangıç 2 (x₁)"); - logs = NumericalMethods.Method_Secant(eq, minX, maxX, iterCount, variable); + string line = stepLogs[i]; + if (line.Contains("BULUNAN KÖK") || line.Contains("Root found:") || line.Contains($"{variable} =") || line.Contains("x =")) + { + rootFound = line; + break; + } } - else // Regula Falsi - { - decimal minX = ParseDecimal(txtMinX.Text, "Alt Sınır (a)"); - decimal maxX = ParseDecimal(txtMaxX.Text, "Üst Sınır (b)"); - logs = NumericalMethods.Method_RegulaFalsi(eq, minX, maxX, iterCount, variable); - } - } - finally - { - Function.UseRadians = prevRad; - } + + return (stepLogs, rootFound); + }); txtResult.Text = string.Join(Environment.NewLine, logs); - // Extract final root from logs - string finalRoot = ""; - for (int i = logs.Count - 1; i >= 0; i--) - { - string line = logs[i]; - if (line.Contains("BULUNAN KÖK") || line.Contains("Root found:") || line.Contains($"{variable} =") || line.Contains("x =")) - { - finalRoot = line; - break; - } - } - if (!string.IsNullOrEmpty(finalRoot)) { string displayRoot = finalRoot.Replace(">>>", "").Replace("BULUNAN KÖK:", "").Replace("Root found:", "").Trim(); @@ -190,6 +203,12 @@ namespace MathApp.Controls lblRootValue.ForeColor = Color.FromArgb(239, 68, 68); lblRootDetails.Text = ex.Message; } + finally + { + btnFindRoot.Enabled = true; + btnFindRoot.Text = origBtnText; + Cursor = Cursors.Default; + } } } } diff --git a/MathApp/MathApp/Controls/SystemSolverControl.cs b/MathApp/MathApp/Controls/SystemSolverControl.cs index 383d81b..76f660a 100644 --- a/MathApp/MathApp/Controls/SystemSolverControl.cs +++ b/MathApp/MathApp/Controls/SystemSolverControl.cs @@ -4,6 +4,7 @@ using System.Drawing; using System.Globalization; using System.Linq; using System.Text; +using System.Threading.Tasks; using System.Windows.Forms; namespace MathApp.Controls @@ -220,8 +221,13 @@ namespace MathApp.Controls } } - private void BtnSolveSystem_Click(object sender, EventArgs e) + private async void BtnSolveSystem_Click(object sender, EventArgs e) { + string origBtnText = btnSolveSystem.Text; + btnSolveSystem.Enabled = false; + btnSolveSystem.Text = "⏳ Hesaplanıyor..."; + Cursor = Cursors.WaitCursor; + try { int count = equationsInputs.Count; @@ -268,37 +274,42 @@ namespace MathApp.Controls iterCount = 50; int methodIdx = cmbSolverMethod.SelectedIndex; - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - Dictionary results; - List stepLogs; - try + + var (results, stepLogs) = await Task.Run(() => { - if (methodIdx == 0) // Multivariable Newton-Raphson + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + Dictionary resDict; + List logs; + try { - results = NumericalMethods.SolveEquationSystemWithLogs(eqs, dict, iterCount, out stepLogs); + if (methodIdx == 0) // Multivariable Newton-Raphson + { + resDict = NumericalMethods.SolveEquationSystemWithLogs(eqs, dict, iterCount, out logs); + } + else if (methodIdx == 1) // Gauss-Seidel + { + resDict = NumericalMethods.Method_GaussSeidel(eqs, dict, iterCount, out logs); + } + else if (methodIdx == 2) // LU Decomposition + { + resDict = NumericalMethods.Method_LinearMatrixSolve(eqs, dict.Keys.ToList(), "LU", out logs); + } + else if (methodIdx == 3) // Inverse Matrix + { + resDict = NumericalMethods.Method_LinearMatrixSolve(eqs, dict.Keys.ToList(), "INVERSE", out logs); + } + else // QR Decomposition + { + resDict = NumericalMethods.Method_LinearMatrixSolve(eqs, dict.Keys.ToList(), "QR", out logs); + } } - else if (methodIdx == 1) // Gauss-Seidel + finally { - results = NumericalMethods.Method_GaussSeidel(eqs, dict, iterCount, out stepLogs); + Function.UseRadians = prevRad; } - else if (methodIdx == 2) // LU Decomposition - { - results = NumericalMethods.Method_LinearMatrixSolve(eqs, dict.Keys.ToList(), "LU", out stepLogs); - } - else if (methodIdx == 3) // Inverse Matrix - { - results = NumericalMethods.Method_LinearMatrixSolve(eqs, dict.Keys.ToList(), "INVERSE", out stepLogs); - } - else // QR Decomposition - { - results = NumericalMethods.Method_LinearMatrixSolve(eqs, dict.Keys.ToList(), "QR", out stepLogs); - } - } - finally - { - Function.UseRadians = prevRad; - } + return (resDict, logs); + }); if (results != null) { @@ -342,6 +353,12 @@ namespace MathApp.Controls lblHeroStatus.Text = ex.Message; txtSystemResult.Text = "❌ Hata: " + ex.Message; } + finally + { + btnSolveSystem.Enabled = true; + btnSolveSystem.Text = origBtnText; + Cursor = Cursors.Default; + } } } } diff --git a/MathApp/MathApp/Controls/TaylorSeriesControl.cs b/MathApp/MathApp/Controls/TaylorSeriesControl.cs index 0b1c2c9..6793e62 100644 --- a/MathApp/MathApp/Controls/TaylorSeriesControl.cs +++ b/MathApp/MathApp/Controls/TaylorSeriesControl.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; +using System.Threading.Tasks; using System.Windows.Forms; namespace MathApp.Controls @@ -48,8 +49,13 @@ namespace MathApp.Controls BtnCalculate_Click(this, EventArgs.Empty); } - private void BtnCalculate_Click(object sender, EventArgs e) + private async void BtnCalculate_Click(object sender, EventArgs e) { + string origBtnText = btnCalculate.Text; + btnCalculate.Enabled = false; + btnCalculate.Text = "⏳ Hesaplanıyor..."; + Cursor = Cursors.WaitCursor; + try { string eq = txtFunction.Text.Trim(); @@ -71,29 +77,33 @@ namespace MathApp.Controls return; } - bool prevRad = Function.UseRadians; - Function.UseRadians = true; - string series; - List derivLines = new List(); - try + var (series, derivLines) = await Task.Run(() => { - decimal f0 = NumericalMethods.Method_EvaluateFunction(eq, variable, center); - derivLines.Add($" f({center}) = {Math.Round(f0, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); - - for (int k = 1; k <= degree; k++) + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + string polySeries; + List lines = new List(); + try { - decimal step = k >= 4 ? 0.01m : 0.005m; - decimal dk = NumericalMethods.Method_NumericalDifferentiation(eq, k, variable, center, 4, step); - decimal coeff = dk / NumericalMethods.Factorial(k); - derivLines.Add($" f^({k})({center}) = {Math.Round(dk, 5).ToString("0.#####", CultureInfo.InvariantCulture),-14} => Katsayı (c_{k}) = {Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); - } + decimal f0 = NumericalMethods.Method_EvaluateFunction(eq, variable, center); + lines.Add($" f({center}) = {Math.Round(f0, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); - series = NumericalMethods.Method_TaylorSeries(eq, degree, variable, center); - } - finally - { - Function.UseRadians = prevRad; - } + for (int k = 1; k <= degree; k++) + { + decimal step = k >= 4 ? 0.01m : 0.005m; + decimal dk = NumericalMethods.Method_NumericalDifferentiation(eq, k, variable, center, 4, step); + decimal coeff = dk / NumericalMethods.Factorial(k); + lines.Add($" f^({k})({center}) = {Math.Round(dk, 5).ToString("0.#####", CultureInfo.InvariantCulture),-14} => Katsayı (c_{k}) = {Math.Round(coeff, 6).ToString("0.######", CultureInfo.InvariantCulture)}"); + } + + polySeries = NumericalMethods.Method_TaylorSeries(eq, degree, variable, center); + } + finally + { + Function.UseRadians = prevRad; + } + return (polySeries, lines); + }); lblHeroPolyValue.Text = $"P_{degree}({variable}) = {series}"; lblHeroPolyValue.ForeColor = Color.FromArgb(52, 211, 153); @@ -110,6 +120,12 @@ namespace MathApp.Controls lblHeroPolyValue.Text = "Hata Oluştu"; lblHeroPolyValue.ForeColor = Color.FromArgb(239, 68, 68); } + finally + { + btnCalculate.Enabled = true; + btnCalculate.Text = origBtnText; + Cursor = Cursors.Default; + } } } } diff --git a/MathApp/MathApp/MainForm.cs b/MathApp/MathApp/MainForm.cs index 2165198..aba0d07 100644 --- a/MathApp/MathApp/MainForm.cs +++ b/MathApp/MathApp/MainForm.cs @@ -17,10 +17,24 @@ namespace MathApp private MultivariableTaylorControl multiTaylorControl; private CombinatoricsControl combinatoricsControl; private GraphPlotterControl graphControl; + private UserControl[] allControls; + + protected override CreateParams CreateParams + { + get + { + CreateParams cp = base.CreateParams; + // WS_EX_COMPOSITED (0x02000000) paints all descendants in bottom-to-top order using double-buffering. + // Eliminates window tearing and redraw flicker. + cp.ExStyle |= 0x02000000; + return cp; + } + } public MainForm() { InitializeComponent(); + ThemeHelper.EnableDoubleBuffering(this); LoadApplicationIcon(); ThemeHelper.ApplyTheme(this); @@ -69,14 +83,49 @@ namespace MathApp multiTaylorControl = new MultivariableTaylorControl { Dock = DockStyle.Fill }; combinatoricsControl = new CombinatoricsControl { Dock = DockStyle.Fill }; graphControl = new GraphPlotterControl { Dock = DockStyle.Fill }; + + allControls = new UserControl[] { + calcControl, + rootControl, + systemControl, + matrixControl, + derivativeControl, + taylorControl, + multiTaylorControl, + combinatoricsControl, + graphControl + }; + + pnlContent.SuspendLayout(); + // Pre-add all controls once to avoid Win32 HWND re-creation and flickering on tab switch + pnlContent.Controls.AddRange(allControls); + foreach (var ctrl in allControls) + { + ctrl.Visible = false; + ThemeHelper.EnableDoubleBuffering(ctrl); + } + pnlContent.ResumeLayout(false); } private void ShowControl(UserControl control) { + if (control == null || allControls == null) return; + pnlContent.SuspendLayout(); - pnlContent.Controls.Clear(); - pnlContent.Controls.Add(control); - pnlContent.ResumeLayout(); + foreach (var ctrl in allControls) + { + if (ctrl != control && ctrl.Visible) + { + ctrl.Visible = false; + } + } + + if (!control.Visible) + { + control.Visible = true; + } + control.BringToFront(); + pnlContent.ResumeLayout(true); } private void HighlightButton(Button activeBtn) diff --git a/MathApp/MathApp/MathApp.Tests/MathApp.Tests.csproj b/MathApp/MathApp/MathApp.Tests/MathApp.Tests.csproj index 74abf5c..91b464a 100644 --- a/MathApp/MathApp/MathApp.Tests/MathApp.Tests.csproj +++ b/MathApp/MathApp/MathApp.Tests/MathApp.Tests.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net8.0 enable enable diff --git a/MathApp/MathApp/MathApp.csproj b/MathApp/MathApp/MathApp.csproj index 00b66aa..db31d66 100644 --- a/MathApp/MathApp/MathApp.csproj +++ b/MathApp/MathApp/MathApp.csproj @@ -9,7 +9,7 @@ logo.ico ttCalculator ttCalculator - Gelişmiş Matematik & Nümerik Analiz Stüdyosu - 2.0.0 + 2.1.0 ttCalculator $(DefaultItemExcludes);MathApp.Tests\** diff --git a/MathApp/MathApp/ThemeHelper.cs b/MathApp/MathApp/ThemeHelper.cs index 1f0e220..16a206e 100644 --- a/MathApp/MathApp/ThemeHelper.cs +++ b/MathApp/MathApp/ThemeHelper.cs @@ -148,5 +148,21 @@ namespace MathApp btn.FlatAppearance.MouseOverBackColor = ButtonHover; return btn; } + + public static void EnableDoubleBuffering(Control control) + { + if (control == null) return; + try + { + var prop = typeof(Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + prop?.SetValue(control, true, null); + } + catch { } + + foreach (Control child in control.Controls) + { + EnableDoubleBuffering(child); + } + } } }