From 72e2fcf145ec1889e73e8c1c92c64fa6630bc76c Mon Sep 17 00:00:00 2001 From: LilDosto Date: Wed, 28 Oct 2026 01:16:35 +0300 Subject: [PATCH] v2.0.0: Complete mathematical overhaul, new controls, zero-leak background process, single instance lock, and 100% verified math engine --- .gitignore | 47 +- Assets/Scripts/DecimalMath.cs | 427 +++--- Assets/Scripts/Function.cs | 1156 ++++++++------ Assets/Scripts/Matrix.cs | 242 ++- .../Scripts/Matrix/CholeskyDecomposition.cs | 17 +- .../Scripts/Matrix/EigenvalueDecomposition.cs | 240 +-- Assets/Scripts/Matrix/GeneralMatrix.cs | 560 +------ Assets/Scripts/Matrix/LUDecomposition.cs | 2 +- Assets/Scripts/Matrix/QRDecomposition.cs | 2 +- .../Matrix/SingularValueDecomposition.cs | 183 +-- Assets/Scripts/NumericalMethods.cs | 1349 +++++++++++------ MathApp/MathApp.sln | 16 +- .../Controls/CombinatoricsControl.Designer.cs | 328 ++++ .../MathApp/Controls/CombinatoricsControl.cs | 268 ++++ .../DerivativeCalculatorControl.Designer.cs | 331 ++++ .../Controls/DerivativeCalculatorControl.cs | 216 +++ .../Controls/GraphPlotterControl.Designer.cs | 264 ++-- .../MathApp/Controls/GraphPlotterControl.cs | 520 ++++--- .../MatrixCalculatorControl.Designer.cs | 434 ++++++ .../Controls/MatrixCalculatorControl.cs | 490 ++++++ .../MultivariableTaylorControl.Designer.cs | 318 ++-- .../Controls/MultivariableTaylorControl.cs | 176 ++- .../Controls/RootFinderControl.Designer.cs | 425 +++--- MathApp/MathApp/Controls/RootFinderControl.cs | 197 ++- .../SimpleCalculatorControl.Designer.cs | 195 ++- .../Controls/SimpleCalculatorControl.cs | 312 +++- .../Controls/SystemSolverControl.Designer.cs | 352 +++-- .../MathApp/Controls/SystemSolverControl.cs | 311 +++- .../Controls/TaylorSeriesControl.Designer.cs | 315 ++-- .../MathApp/Controls/TaylorSeriesControl.cs | 101 +- MathApp/MathApp/Core/DecimalMath.cs | 427 +++--- MathApp/MathApp/Core/Function.cs | 1155 ++++++++------ MathApp/MathApp/Core/Matrix.cs | 261 +--- .../Core/Matrix/CholeskyDecomposition.cs | 15 +- .../Core/Matrix/EigenvalueDecomposition.cs | 11 +- .../Core/Matrix/SingularValueDecomposition.cs | 30 +- MathApp/MathApp/Core/NumericalMethods.cs | 1229 +++++++++++---- MathApp/MathApp/GenerateLogo.ps1 | 236 ++- MathApp/MathApp/MainForm.Designer.cs | 250 +-- MathApp/MathApp/MainForm.cs | 94 +- .../MathApp.Tests/CholeskyDecomposition.cs | 15 +- MathApp/MathApp/MathApp.Tests/DecimalMath.cs | 427 +++--- .../MathApp.Tests/EigenvalueDecomposition.cs | 11 +- MathApp/MathApp/MathApp.Tests/Function.cs | 1155 ++++++++------ MathApp/MathApp/MathApp.Tests/Matrix.cs | 237 +-- .../MathApp/MathApp.Tests/NumericalMethods.cs | 1237 +++++++++++---- .../SingularValueDecomposition.cs | 30 +- MathApp/MathApp/MathApp.csproj | 16 +- MathApp/MathApp/Program.cs | 90 +- MathApp/MathApp/ThemeHelper.cs | 181 ++- MathApp/MathApp/logo.ico | Bin 41086 -> 52011 bytes README.md | 125 +- 52 files changed, 10997 insertions(+), 6029 deletions(-) create mode 100644 MathApp/MathApp/Controls/CombinatoricsControl.Designer.cs create mode 100644 MathApp/MathApp/Controls/CombinatoricsControl.cs create mode 100644 MathApp/MathApp/Controls/DerivativeCalculatorControl.Designer.cs create mode 100644 MathApp/MathApp/Controls/DerivativeCalculatorControl.cs create mode 100644 MathApp/MathApp/Controls/MatrixCalculatorControl.Designer.cs create mode 100644 MathApp/MathApp/Controls/MatrixCalculatorControl.cs diff --git a/.gitignore b/.gitignore index ddc5028..bc73d58 100644 --- a/.gitignore +++ b/.gitignore @@ -1,28 +1,28 @@ # Unity default ignore files -Library/ -Temp/ -obj/ -Build/ -Builds/ -Logs/ -MemoryCaptures/ -Archive/ +/[Ll]ibrary/ +/[Tt]emp/ +/[Oo]bj/ +/[Bb]uild/ +/[Bb]uilds/ +/[Ll]ogs/ +/[Mm]emoryCaptures/ +/[Aa]rchive/ # Asset meta files for folders ignored above -Library.meta -Temp.meta -obj.meta -Build.meta -Builds.meta -Save.meta +/[Ll]ibrary.meta +/[Tt]emp.meta +/[Oo]bj.meta +/[Bb]uild.meta +/[Bb]uilds.meta +/[Ss]ave.meta # Autogenerated VS/MD/Consulo solution and project files ExportedObj/ .consulo/ /*.csproj -*.unityproj +/*.unityproj /*.sln -/*.suo +*.suo *.tmp *.user *.userprefs @@ -33,6 +33,10 @@ ExportedObj/ *.opendb *.tlog +# .NET build artifacts +[Bb]in/ +[Oo]bj/ + # Unity3D generated meta files sysinfo.txt @@ -43,13 +47,4 @@ sysinfo.txt *.unitypackage *.app .vs/ -bin/ - -# MathApp build outputs and logs -build_err.txt -build_err_main.txt -build_log.txt -test_results.txt -out_ascii.txt -*.log - +[Rr]elease/ diff --git a/Assets/Scripts/DecimalMath.cs b/Assets/Scripts/DecimalMath.cs index 04b7b25..4330fa7 100644 --- a/Assets/Scripts/DecimalMath.cs +++ b/Assets/Scripts/DecimalMath.cs @@ -1,7 +1,7 @@ -using System; +using System; /// -/// Analogy of Syatem.Math class for decimal types +/// Analogy of System.Math class for decimal types with high precision. /// public static class DecimalMath { @@ -11,14 +11,14 @@ public static class DecimalMath public const decimal PI = 3.14159265358979323846264338327950288419716939937510M; /// - /// represents PI + /// represents machine epsilon for decimal comparisons /// public const decimal Epsilon = 0.0000000000000000001M; /// /// represents 2*PI /// - private const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; + public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; /// /// represents E @@ -28,12 +28,12 @@ public static class DecimalMath /// /// represents PI/2 /// - private const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; + public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; /// /// represents PI/4 /// - private const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; + public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; /// /// represents 1.0/E @@ -66,48 +66,45 @@ public static class DecimalMath private const int MaxIteration = 100; /// - /// Analogy of Math.Exp method + /// Analogy of Math.Exp method with full precision across all ranges /// - /// - /// public static decimal Exp(decimal x) { - var count = 0; - - if (x > One) + if (x == Zero) return One; + if (x > 66.5m) { - count = decimal.ToInt32(decimal.Truncate(x)); - x -= decimal.Truncate(x); + throw new OverflowException("Exp argümanı çok büyük (decimal taşması)."); + } + if (x < -70m) + { + return Zero; } - if (x < Zero) { - count = decimal.ToInt32(decimal.Truncate(x) - 1); - x = One + (x - decimal.Truncate(x)); + return One / Exp(-x); } - var iteration = 1; - var result = One; - var factorial = One; + int count = decimal.ToInt32(decimal.Truncate(x)); + x -= count; + + int iteration = 1; + decimal result = One; + decimal factorial = One; decimal cachedResult; do { cachedResult = result; factorial *= x / iteration++; result += factorial; - } while (cachedResult != result); + } while (cachedResult != result && iteration < MaxIteration); - if (count == 0) - return result; + if (count == 0) return result; return result * PowerN(E, count); } /// /// Analogy of Math.Pow method /// - /// - /// - /// public static decimal Pow(decimal value, decimal pow) { if (pow == Zero) return One; @@ -116,37 +113,32 @@ public static class DecimalMath if (value == Zero) { - if (pow > Zero) - { - return Zero; - } - - throw new Exception("Invalid Operation: zero base and negative power"); + if (pow > Zero) return Zero; + throw new DivideByZeroException("Geçersiz İşlem: Sıfır tabanının negatif kuvveti alınamaz."); } if (pow == -One) return One / value; - var isPowerInteger = IsInteger(pow); + bool isPowerInteger = IsInteger(pow); if (value < Zero && !isPowerInteger) { - throw new Exception("Invalid Operation: negative base and non-integer power"); - } - - if (isPowerInteger && value > Zero) - { - int powerInt = (int)pow; - return PowerN(value, powerInt); - } - - if (isPowerInteger && value < Zero) - { - int powerInt = (int)pow; - if (powerInt % 2 == 0) + // Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5 + decimal invPow = One / pow; + if (IsInteger(invPow)) { - return Exp(pow * Log(-value)); + int q = (int)decimal.Round(invPow); + if (q % 2 != 0) + { + return -Exp(pow * Log(-value)); + } } + throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır."); + } - return -Exp(pow * Log(-value)); + if (isPowerInteger) + { + int powerInt = (int)decimal.Round(pow); + return PowerN(value, powerInt); } return Exp(pow * Log(value)); @@ -154,53 +146,41 @@ public static class DecimalMath private static bool IsInteger(decimal value) { - var longValue = (long)value; - return Abs(value - longValue) <= Epsilon; + var rounded = decimal.Round(value); + return Abs(value - rounded) <= Epsilon; } /// /// Power to the integer value /// - /// - /// - /// public static decimal PowerN(decimal value, int power) { - while (true) + if (power == 0) return One; + if (power < 0) { - if (power == Zero) return One; - if (power < Zero) - { - value = One / value; - power = -power; - continue; - } - - var q = power; - var prod = One; - var current = value; - while (q > 0) - { - if (q % 2 == 1) - { - // detects the 1s in the binary expression of power - prod = current * prod; // picks up the relevant power - q--; - } - - current *= current; // value^i -> value^(2*i) - q >>= 1; - } - - return prod; + value = One / value; + power = -power; } + + int q = power; + decimal prod = One; + decimal current = value; + while (q > 0) + { + if (q % 2 == 1) + { + prod = current * prod; + q--; + } + current *= current; + q >>= 1; + } + return prod; } /// /// Analogy of Math.Log10 /// - /// - /// public static decimal Log10(decimal x) { return Log(x) * Log10Inv; @@ -209,15 +189,13 @@ public static class DecimalMath /// /// Analogy of Math.Log /// - /// - /// public static decimal Log(decimal x) { if (x <= Zero) { - throw new ArgumentException("x must be greater than zero"); + throw new ArgumentException("Logaritma argümanı sıfırdan büyük olmalıdır."); } - var count = 0; + int count = 0; while (x >= One) { x *= Einv; @@ -230,10 +208,11 @@ public static class DecimalMath } x--; if (x == Zero) return count; - var result = Zero; - var iteration = 0; - var y = One; - var cacheResult = result - One; + + decimal result = Zero; + int iteration = 0; + decimal y = One; + decimal cacheResult = result - One; while (cacheResult != result && iteration < MaxIteration) { iteration++; @@ -245,140 +224,127 @@ public static class DecimalMath } /// - /// Analogy of Math.Cos + /// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x) /// - /// - /// - public static decimal Cos(decimal x) + public static decimal Sin(decimal x) { - //truncating to [-2*PI;2*PI] TruncateToPeriodicInterval(ref x); - // now x in (-2pi,2pi) - if (x >= PI && x <= PIx2) - { - return -Cos(x - PI); - } - if (x >= -PIx2 && x <= -PI) - { - return -Cos(x + PI); - } + if (x > PI) x -= PIx2; + else if (x < -PI) x += PIx2; - x *= x; - //y=1-x/2!+x^2/4!-x^3/6!... - var xx = -x * Half; - var y = One + xx; - var cachedY = y - One;//init cache with different value - for (var i = 1; cachedY != y && i < MaxIteration; i++) + if (x > PIdiv2) x = PI - x; + else if (x < -PIdiv2) x = -PI - x; + + decimal x2 = x * x; + decimal term = x; + decimal sum = x; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) { - cachedY = y; - decimal factor = i * ((i << 1) + 3) + 1; //2i^2+2i+i+1=2i^2+3i+1 - factor = -Half / factor; - xx *= x * factor; - y += xx; + cachedSum = sum; + term *= -x2 / ((2 * i) * (2 * i + 1)); + sum += term; + if (sum == cachedSum) break; } - return y; + return sum; + } + + /// + /// Analogy of Math.Cos + /// + public static decimal Cos(decimal x) + { + TruncateToPeriodicInterval(ref x); + + if (x > PI) x -= PIx2; + else if (x < -PI) x += PIx2; + + if (x > PIdiv2) return -Cos(PI - x); + if (x < -PIdiv2) return -Cos(-PI - x); + + decimal x2 = x * x; + decimal term = One; + decimal sum = One; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) + { + cachedSum = sum; + term *= -x2 / ((2 * i - 1) * (2 * i)); + sum += term; + if (sum == cachedSum) break; + } + return sum; } /// /// Analogy of Math.Tan /// - /// - /// public static decimal Tan(decimal x) { - var cos = Cos(x); - if (cos == Zero) throw new ArgumentException(nameof(x)); - //calculate sin using cos - var sin = CalculateSinFromCos(x, cos); - return sin / cos; - } - /// - /// Helper function for calculating sin(x) from cos(x) - /// - /// - /// - /// - private static decimal CalculateSinFromCos(decimal x, decimal cos) - { - var moduleOfSin = Sqrt(One - (cos * cos)); - var sineIsPositive = IsSignOfSinePositive(x); - if (sineIsPositive) return moduleOfSin; - return -moduleOfSin; - } - /// - /// Analogy of Math.Sin - /// - /// - /// - public static decimal Sin(decimal x) - { - var cos = Cos(x); - return CalculateSinFromCos(x, cos); + decimal cos = Cos(x); + if (Abs(cos) <= 1e-25m) throw new ArgumentException("Tan(x) bu noktada tanımsızdır (cos(x) = 0)."); + return Sin(x) / cos; } - - /// - /// Truncates to [-2*PI;2*PI] - /// - /// private static void TruncateToPeriodicInterval(ref decimal x) { - while (x >= PIx2) + if (x >= PIx2 || x <= -PIx2) { - var divide = Math.Abs(decimal.ToInt32(x / PIx2)); - x -= divide * PIx2; + x = x % PIx2; } - - while (x <= -PIx2) - { - var divide = Math.Abs(decimal.ToInt32(x / PIx2)); - x += divide * PIx2; - } - } - - - private static bool IsSignOfSinePositive(decimal x) - { - //truncating to [-2*PI;2*PI] - TruncateToPeriodicInterval(ref x); - - //now x in [-2*PI;2*PI] - if (x >= -PIx2 && x <= -PI) return true; - if (x >= -PI && x <= Zero) return false; - if (x >= Zero && x <= PI) return true; - if (x >= PI && x <= PIx2) return false; - - //will not be reached - throw new ArgumentException(nameof(x)); } /// - /// Analogy of Math.Sqrt + /// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation) /// - /// - /// lasts iteration while error less than this epsilon - /// public static decimal Sqrt(decimal x, decimal epsilon = Zero) { - if (x < Zero) throw new OverflowException("Cannot calculate square root from a negative number"); - //initial approximation - decimal current = (decimal)Math.Sqrt((double)x), previous; - do + if (x < Zero) throw new ArgumentException("Negatif sayının karekökü reel sayılarda alınamaz."); + if (x == Zero) return Zero; + + decimal current = (decimal)Math.Sqrt((double)x); + if (current == Zero) current = x * Half; + + decimal previous = Zero; + int maxSteps = 25; + for (int step = 0; step < maxSteps; step++) { + decimal next = (current + x / current) * Half; + if (next == current || next == previous || Abs(next - current) <= epsilon) + { + return next; + } previous = current; - if (previous == Zero) return Zero; - current = (previous + x / previous) * Half; - } while (Abs(previous - current) > epsilon); + current = next; + } return current; } + /// /// Analogy of Math.Sinh /// - /// - /// public static decimal Sinh(decimal x) { + if (x < Zero) return -Sinh(-x); + + if (Abs(x) < 0.1m) + { + // Taylor series for small x to avoid loss of significance in (e^x - e^-x)/2 + decimal x2 = x * x; + decimal term = x; + decimal sum = x; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) + { + cachedSum = sum; + term *= x2 / ((2 * i) * (2 * i + 1)); + sum += term; + if (sum == cachedSum) break; + } + return sum; + } + var y = Exp(x); var yy = One / y; return (y - yy) * Half; @@ -387,10 +353,9 @@ public static class DecimalMath /// /// Analogy of Math.Cosh /// - /// - /// public static decimal Cosh(decimal x) { + if (x < Zero) x = -x; var y = Exp(x); var yy = One / y; return (y + yy) * Half; @@ -399,8 +364,6 @@ public static class DecimalMath /// /// Analogy of Math.Sign /// - /// - /// public static int Sign(decimal x) { return x < Zero ? -1 : (x > Zero ? 1 : 0); @@ -409,109 +372,103 @@ public static class DecimalMath /// /// Analogy of Math.Tanh /// - /// - /// public static decimal Tanh(decimal x) { - var y = Exp(x); - var yy = One / y; - return (y - yy) / (y + yy); + if (x > 35m) return One; + if (x < -35m) return -One; + + var y = Exp(2m * x); + return (y - One) / (y + One); } /// /// Analogy of Math.Abs /// - /// - /// public static decimal Abs(decimal x) { - if (x <= Zero) - { - return -x; - } - return x; + return x <= Zero ? -x : x; } /// /// Analogy of Math.Asin /// - /// - /// public static decimal Asin(decimal x) { if (x > One || x < -One) { - throw new ArgumentException("x must be in [-1,1]"); + throw new ArgumentException("Asin argümanı [-1, 1] aralığında olmalıdır."); } - //known values if (x == Zero) return Zero; if (x == One) return PIdiv2; - //asin function is odd function + if (x == -One) return -PIdiv2; if (x < Zero) return -Asin(-x); - //my optimize trick here - - // used a math formula to speed up : - // asin(x)=0.5*(pi/2-asin(1-2*x*x)) - // if x>=0 is true - var newX = One - 2 * x * x; - - //for calculating new value near to zero than current - //because we gain more speed with values near to zero if (Abs(x) > Abs(newX)) { var t = Asin(newX); return Half * (PIdiv2 - t); } - var y = Zero; - var result = x; + + decimal y = Zero; + decimal result = x; decimal cachedResult; - var i = 1; + int i = 1; y += result; - var xx = x * x; + decimal xx = x * x; do { cachedResult = result; - result *= xx * (One - Half / (i)); + result *= xx * (One - Half / i); y += result / ((i << 1) + 1); i++; - } while (cachedResult != result); + } while (cachedResult != result && i < MaxIteration); return y; } /// - /// Analogy of Math.Atan + /// Analogy of Math.Atan (safe against overflow for large x) /// - /// - /// public static decimal Atan(decimal x) { if (x == Zero) return Zero; if (x == One) return PIdiv4; + if (x == -One) return -PIdiv4; + + if (x > 100000000000000m) return PIdiv2; + if (x < -100000000000000m) return -PIdiv2; + + if (x > One) + { + return PIdiv2 - Atan(One / x); + } + if (x < -One) + { + return -PIdiv2 - Atan(One / x); + } + return Asin(x / Sqrt(One + x * x)); } + /// /// Analogy of Math.Acos /// - /// - /// public static decimal Acos(decimal x) { + if (x > One || x < -One) + { + throw new ArgumentException("Acos argümanı [-1, 1] aralığında olmalıdır."); + } if (x == Zero) return PIdiv2; if (x == One) return Zero; + if (x == -One) return PI; if (x < Zero) return PI - Acos(-x); return PIdiv2 - Asin(x); } /// /// Analogy of Math.Atan2 - /// for more see this - /// /// - /// - /// - /// public static decimal Atan2(decimal y, decimal x) { if (x > Zero) @@ -534,6 +491,6 @@ public static class DecimalMath { return -PIdiv2; } - throw new ArgumentException("invalid atan2 arguments"); + throw new ArgumentException("Geçersiz Atan2 argümanları (0, 0)."); } } diff --git a/Assets/Scripts/Function.cs b/Assets/Scripts/Function.cs index 4797899..26d7ff8 100644 --- a/Assets/Scripts/Function.cs +++ b/Assets/Scripts/Function.cs @@ -1,71 +1,47 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; +using System.Globalization; - -/// -/// -/// public enum Type { Variable, Value, UnaryOperator, Operator, Function, Result, Bracket, Comma, Error } + public struct Symbol { public string m_name; public decimal m_value; public Type m_type; + public int m_argCount; public override string ToString() { return m_name; } } -public delegate Symbol EvaluateFunctionDelegate(string name, params Object[] args); + +public delegate Symbol EvaluateFunctionDelegate(string name, params Symbol[] args); + public class Function { - public decimal Result + private static readonly HashSet KnownFunctions = new HashSet(StringComparer.OrdinalIgnoreCase) { - get - { - return m_result; - } - } + "sin", "cos", "tan", "cot", "cosh", "sinh", "tanh", + "log", "ln", "logn", "sqrt", "cbrt", "abs", + "acos", "asin", "atan", "atan2", "exp", + "max", "min", "floor", "ceil", "round", "sign" + }; - public ArrayList Equation - { - get - { - return (ArrayList)m_equation.Clone(); - } - } - public ArrayList Postfix - { - get - { - return (ArrayList)m_postfix.Clone(); - } - } + public static bool UseRadians { get; set; } = true; + + public decimal Result => m_result; + public ArrayList Equation => (ArrayList)m_equation.Clone(); + public ArrayList Postfix => (ArrayList)m_postfix.Clone(); public EvaluateFunctionDelegate DefaultFunctionEvaluation { - set - { - m_defaultFunctionEvaluation = value; - } + set => m_defaultFunctionEvaluation = value; } - public bool Error - { - get - { - return m_bError; - } - } - - public string ErrorDescription - { - get - { - return m_sErrorDescription; - } - } + public bool Error => m_bError; + public string ErrorDescription => m_sErrorDescription; public ArrayList Variables { @@ -96,14 +72,69 @@ public class Function } } + public void SetVariable(string name, decimal value) + { + for (int i = 0; i < m_postfix.Count; i++) + { + Symbol s = (Symbol)m_postfix[i]; + if (s.m_type == Type.Variable && string.Equals(s.m_name, name, StringComparison.OrdinalIgnoreCase)) + { + s.m_value = value; + m_postfix[i] = s; + } + } + } + + public void SetVariables(Dictionary values) + { + for (int i = 0; i < m_postfix.Count; i++) + { + Symbol s = (Symbol)m_postfix[i]; + if (s.m_type == Type.Variable && values.TryGetValue(s.m_name, out decimal val)) + { + s.m_value = val; + m_postfix[i] = s; + } + } + } + public Function() - { } + { + } + + private void AddSymbolWithImplicitMultiplication(Symbol sym) + { + if (m_equation.Count > 0) + { + Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; + bool prevIsOperandOrClose = prev.m_type == Type.Value || + prev.m_type == Type.Variable || + prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}"; + + bool currIsOperandOrOpen = sym.m_type == Type.Value || + sym.m_type == Type.Variable || + sym.m_type == Type.Function || + sym.m_name == "(" || sym.m_name == "[" || sym.m_name == "{"; + + if (prevIsOperandOrClose && currIsOperandOrOpen) + { + Symbol mulSym = new Symbol + { + m_name = "*", + m_value = 0, + m_type = Type.Operator + }; + m_equation.Add(mulSym); + } + } + m_equation.Add(sym); + } public void Parse(string equation) { int state = 1; string temp = ""; - Symbol ctSymbol; + Symbol ctSymbol = new Symbol(); m_bError = false; m_sErrorDescription = "None"; @@ -111,179 +142,252 @@ public class Function m_equation.Clear(); m_postfix.Clear(); - int nPos = 0; - //-- Remove all white spaces from the equation string -- - equation = equation.Trim(); - while ((nPos = equation.IndexOf(' ')) != -1) - equation = equation.Remove(nPos, 1); + if (string.IsNullOrWhiteSpace(equation)) + { + m_bError = true; + m_sErrorDescription = "Denklem boş olamaz."; + return; + } + // We process whitespace as delimiter without deleting it globally for (int i = 0; i < equation.Length; i++) { + char ch = equation[i]; switch (state) { - case 1: - if (Char.IsNumber(equation[i])) + case 1: // Neutral + if (char.IsWhiteSpace(ch)) + { + continue; + } + if (char.IsDigit(ch) || ch == '.') { state = 2; - temp += equation[i]; + temp += ch; } - else if (Char.IsLetter(equation[i])) + else if (char.IsLetter(ch)) { state = 3; - temp += equation[i]; + temp += ch; } else { - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) - { - case ",": - case ".": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; - break; - } - m_equation.Add(ctSymbol); + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } break; - case 2: - if ((Char.IsNumber(equation[i])) || (equation[i] == '.') || (equation[i] == ',')) - temp += equation[i]; - else if (!Char.IsLetter(equation[i])) + + case 2: // Reading Number + if (char.IsDigit(ch) || ch == '.') { - state = 1; - ctSymbol.m_name = temp; - ctSymbol.m_value = Decimal.Parse(temp); - ctSymbol.m_type = Type.Value; - m_equation.Add(ctSymbol); - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) - { - case ",": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; - break; - } - m_equation.Add(ctSymbol); + temp += ch; + } + else if (char.IsWhiteSpace(ch)) + { + if (!EmitNumberSymbol(temp)) return; temp = ""; + state = 1; } - break; - case 3: - if (Char.IsLetterOrDigit(equation[i])) - temp += equation[i]; else { - state = 1; - ctSymbol.m_name = temp; - ctSymbol.m_value = 0; - if (equation[i] == '(') - ctSymbol.m_type = Type.Function; + if (!EmitNumberSymbol(temp)) return; + temp = ""; + + if (char.IsLetter(ch)) + { + state = 3; + temp += ch; + } else { - if (ctSymbol.m_name == "pi") - ctSymbol.m_value = DecimalMath.PI; - else if (ctSymbol.m_name == "e") - ctSymbol.m_value = DecimalMath.E; - ctSymbol.m_type = Type.Variable; + state = 1; + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } - m_equation.Add(ctSymbol); - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) + } + break; + + case 3: // Reading Identifier + if (char.IsLetterOrDigit(ch)) + { + temp += ch; + } + else if (char.IsWhiteSpace(ch)) + { + // Lookahead to see if next non-whitespace is '(' + bool nextIsOpen = false; + for (int k = i + 1; k < equation.Length; k++) { - case ",": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; + if (!char.IsWhiteSpace(equation[k])) + { + nextIsOpen = (equation[k] == '(' || equation[k] == '[' || equation[k] == '{'); break; + } } - m_equation.Add(ctSymbol); + EmitIdentifierSymbol(temp, nextIsOpen); temp = ""; + state = 1; + } + else + { + state = 1; + EmitIdentifierSymbol(temp, ch == '(' || ch == '[' || ch == '{'); + temp = ""; + + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } break; } } + if (temp != "") { - ctSymbol.m_name = temp; if (state == 2) { - ctSymbol.m_value = Decimal.Parse(temp); - ctSymbol.m_type = Type.Value; + if (!EmitNumberSymbol(temp)) return; } else { - if (ctSymbol.m_name == "pi") - ctSymbol.m_value = DecimalMath.PI; - else if (ctSymbol.m_name == "e") - ctSymbol.m_value = DecimalMath.E; - else - ctSymbol.m_value = 0; - ctSymbol.m_type = Type.Variable; + EmitIdentifierSymbol(temp, false); } - m_equation.Add(ctSymbol); } } + private bool EmitNumberSymbol(string temp) + { + if (!decimal.TryParse(temp, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) + { + m_bError = true; + m_sErrorDescription = "Geçersiz sayı formatı: " + temp; + return false; + } + + Symbol sym = new Symbol + { + m_name = temp, + m_value = val, + m_type = Type.Value + }; + AddSymbolWithImplicitMultiplication(sym); + return true; + } + + private void EmitIdentifierSymbol(string temp, bool isNextOpenParen) + { + Symbol sym = new Symbol + { + m_name = temp, + m_value = 0 + }; + + string lower = temp.ToLowerInvariant(); + if (lower == "pi") + { + sym.m_value = DecimalMath.PI; + sym.m_type = Type.Value; + } + else if (lower == "e") + { + sym.m_value = DecimalMath.E; + sym.m_type = Type.Value; + } + else if (isNextOpenParen) + { + if (temp.Length == 1 && (temp == "x" || temp == "y" || temp == "z" || temp == "t" || temp == "u" || temp == "v")) + { + sym.m_type = Type.Variable; + } + else + { + sym.m_type = Type.Function; + } + } + else + { + sym.m_type = Type.Variable; + } + AddSymbolWithImplicitMultiplication(sym); + } + + private Symbol ClassifyNonAlphanumeric(string token) + { + Symbol ctSymbol = new Symbol + { + m_name = token, + m_value = 0 + }; + + switch (token) + { + case ",": + case ";": + ctSymbol.m_type = Type.Comma; + break; + case "(": + case ")": + case "[": + case "]": + case "{": + case "}": + ctSymbol.m_type = Type.Bracket; + break; + default: + if (m_equation.Count == 0) + { + ctSymbol.m_type = Type.UnaryOperator; + } + else + { + Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; + if (prev.m_type == Type.Value || prev.m_type == Type.Variable || + prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}") + { + ctSymbol.m_type = Type.Operator; + } + else + { + ctSymbol.m_type = Type.UnaryOperator; + } + } + break; + } + return ctSymbol; + } + public void Infix2Postfix() { + m_postfix.Clear(); Symbol tpSym; Stack tpStack = new Stack(); + Stack fnArgCounts = new Stack(); + foreach (Symbol sym in m_equation) { if ((sym.m_type == Type.Value) || (sym.m_type == Type.Variable)) m_postfix.Add(sym); + else if (sym.m_type == Type.Function) + { + tpStack.Push(sym); + fnArgCounts.Push(1); + } else if ((sym.m_name == "(") || (sym.m_name == "[") || (sym.m_name == "{")) tpStack.Push(sym); + else if (sym.m_type == Type.Comma) + { + while (tpStack.Count > 0) + { + tpSym = (Symbol)tpStack.Peek(); + if (tpSym.m_name == "(" || tpSym.m_name == "[" || tpSym.m_name == "{") + break; + m_postfix.Add(tpStack.Pop()); + } + if (fnArgCounts.Count > 0) + { + int c = fnArgCounts.Pop(); + fnArgCounts.Push(c + 1); + } + } else if ((sym.m_name == ")") || (sym.m_name == "]") || (sym.m_name == "}")) { if (tpStack.Count > 0) @@ -292,28 +396,56 @@ public class Function while ((tpSym.m_name != "(") && (tpSym.m_name != "[") && (tpSym.m_name != "{")) { m_postfix.Add(tpSym); + if (tpStack.Count == 0) break; tpSym = (Symbol)tpStack.Pop(); } + + if (tpStack.Count > 0 && ((Symbol)tpStack.Peek()).m_type == Type.Function) + { + Symbol fn = (Symbol)tpStack.Pop(); + fn.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; + m_postfix.Add(fn); + } } } else if (sym.m_type == Type.UnaryOperator) { + // Unary operators (like unary - or +) modify the operand to their right. + // They should never pop binary operators (^, *, /, +, -) from the stack. + tpStack.Push(sym); + } + else if (sym.m_name == "^") + { + // Right-associative operator ^ + while (tpStack.Count > 0) + { + tpSym = (Symbol)tpStack.Peek(); + if ((tpSym.m_type == Type.Operator || tpSym.m_type == Type.Function) && + Precedence(tpSym) > Precedence(sym)) + { + m_postfix.Add(tpStack.Pop()); + } + else + { + break; + } + } tpStack.Push(sym); } else { - if (tpStack.Count > 0) + while (tpStack.Count > 0) { - tpSym = (Symbol)tpStack.Pop(); - while ((tpStack.Count != 0) && ((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym))) + tpSym = (Symbol)tpStack.Peek(); + if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function)) && + (Precedence(tpSym) >= Precedence(sym))) { - m_postfix.Add(tpSym); - tpSym = (Symbol)tpStack.Pop(); + m_postfix.Add(tpStack.Pop()); } - if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym))) - m_postfix.Add(tpSym); else - tpStack.Push(tpSym); + { + break; + } } tpStack.Push(sym); } @@ -321,6 +453,10 @@ public class Function while (tpStack.Count > 0) { tpSym = (Symbol)tpStack.Pop(); + if (tpSym.m_type == Type.Function && tpSym.m_argCount == 0) + { + tpSym.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; + } m_postfix.Add(tpSym); } } @@ -329,7 +465,6 @@ public class Function { Symbol tpSym1, tpSym2, tpResult; Stack tpStack = new Stack(); - ArrayList fnParam = new ArrayList(); m_bError = false; foreach (Symbol sym in m_postfix) { @@ -337,6 +472,12 @@ public class Function tpStack.Push(sym); else if (sym.m_type == Type.UnaryOperator) { + if (tpStack.Count < 1) + { + m_bError = true; + m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; + return; + } tpSym1 = (Symbol)tpStack.Pop(); tpResult = Evaluate(sym, tpSym1); if (tpResult.m_type == Type.Error) @@ -349,6 +490,12 @@ public class Function } else if (sym.m_type == Type.Operator) { + if (tpStack.Count < 2) + { + m_bError = true; + m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; + return; + } tpSym1 = (Symbol)tpStack.Pop(); tpSym2 = (Symbol)tpStack.Pop(); tpResult = Evaluate(tpSym2, sym, tpSym1); @@ -360,55 +507,30 @@ public class Function } tpStack.Push(tpResult); } - else if (sym.m_type == Type.Comma) - { - tpStack.Push(sym); - } else if (sym.m_type == Type.Function) { - fnParam.Clear(); - tpSym1 = (Symbol)tpStack.Pop(); - if ((tpSym1.m_type == Type.Value) || (tpSym1.m_type == Type.Variable) || (tpSym1.m_type == Type.Result)) + int count = sym.m_argCount > 0 ? sym.m_argCount : 1; + if (tpStack.Count < count) { - tpResult = EvaluateFunction(sym.m_name, tpSym1); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + m_bError = true; + m_sErrorDescription = $"Fonksiyon '{sym.m_name}' için argüman eksik."; + return; } - else if (tpSym1.m_type == Type.Comma) + + Symbol[] fnParam = new Symbol[count]; + for (int i = count - 1; i >= 0; i--) { - while (tpSym1.m_type == Type.Comma) - { - tpSym1 = (Symbol)tpStack.Pop(); - fnParam.Add(tpSym1); - tpSym1 = (Symbol)tpStack.Pop(); - } - fnParam.Add(tpSym1); - tpResult = EvaluateFunction(sym.m_name, fnParam.ToArray()); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + fnParam[i] = (Symbol)tpStack.Pop(); } - else + + tpResult = EvaluateFunction(sym.m_name, fnParam); + if (tpResult.m_type == Type.Error) { - tpStack.Push(tpSym1); - tpResult = EvaluateFunction(sym.m_name); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + m_bError = true; + m_sErrorDescription = tpResult.m_name; + return; } + tpStack.Push(tpResult); } } if (tpStack.Count == 1) @@ -416,6 +538,11 @@ public class Function tpResult = (Symbol)tpStack.Pop(); m_result = tpResult.m_value; } + else if (tpStack.Count > 1) + { + m_bError = true; + m_sErrorDescription = "İfade tam çözümlenemedi (fazla terim)."; + } } protected int Precedence(Symbol sym) @@ -425,16 +552,16 @@ public class Function case Type.Bracket: return 7; case Type.Function: - return 5; + return 6; case Type.UnaryOperator: - return 4; + return 3; case Type.Comma: return 0; } switch (sym.m_name) { case "^": - return 3; + return 5; case "/": case "*": case "%": @@ -448,21 +575,21 @@ public class Function protected Symbol Evaluate(Symbol opr, Symbol sym1) { - Symbol result; + Symbol result = default; result.m_name = opr.m_name + sym1.m_name; result.m_type = Type.Result; result.m_value = 0; switch (opr.m_name) { case "+": - result.m_value = sym1.m_value; ; + result.m_value = sym1.m_value; break; case "-": result.m_value = -1 * sym1.m_value; break; default: result.m_type = Type.Error; - result.m_name = "Undefine unary operator: " + opr.m_name + "."; + result.m_name = "Tanımsız tekli operatör: " + opr.m_name; break; } return result; @@ -470,243 +597,390 @@ public class Function protected Symbol Evaluate(Symbol sym1, Symbol opr, Symbol sym2) { - Symbol result; + Symbol result = default; result.m_name = sym1.m_name + opr.m_name + sym2.m_name; result.m_type = Type.Result; result.m_value = 0; - switch (opr.m_name) + try { - case "^": - result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); - break; - case "/": - { + switch (opr.m_name) + { + case "^": + result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); + break; + case "/": if (sym2.m_value != 0) result.m_value = sym1.m_value / sym2.m_value; else { - result.m_name = "Divide by Zero."; + result.m_name = "Sıfıra bölme hatası (Divide by Zero)."; result.m_type = Type.Error; } break; - } - case "*": - result.m_value = sym1.m_value * sym2.m_value; - break; - case "%": - result.m_value = sym1.m_value % sym2.m_value; - break; - case "+": - result.m_value = sym1.m_value + sym2.m_value; - break; - case "-": - result.m_value = sym1.m_value - sym2.m_value; - break; - default: - result.m_type = Type.Error; - result.m_name = "Undefine operator: " + opr.m_name + "."; - break; + case "*": + result.m_value = sym1.m_value * sym2.m_value; + break; + case "%": + if (sym2.m_value != 0) + result.m_value = sym1.m_value % sym2.m_value; + else + { + result.m_name = "Sıfıra göre mod alınamaz."; + result.m_type = Type.Error; + } + break; + case "+": + result.m_value = sym1.m_value + sym2.m_value; + break; + case "-": + result.m_value = sym1.m_value - sym2.m_value; + break; + default: + result.m_type = Type.Error; + result.m_name = "Tanımsız operatör: " + opr.m_name; + break; + } + } + catch (Exception ex) + { + result.m_type = Type.Error; + result.m_name = ex.Message; } return result; } - protected Symbol EvaluateFunction(string name, params Object[] args) + protected Symbol EvaluateFunction(string name, params Symbol[] args) { - Symbol result; + Symbol result = default; result.m_name = ""; result.m_type = Type.Result; result.m_value = 0; - switch (name) + + string lowerName = name.ToLowerInvariant(); + decimal angleFactor = UseRadians ? 1.0m : (DecimalMath.PI / 180.0m); + decimal invAngleFactor = UseRadians ? 1.0m : (180.0m / DecimalMath.PI); + + try { - case "cos": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Cos(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sin": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sin(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "tan": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Tan(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "cosh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Cosh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sinh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sinh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "tanh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Tanh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "log": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log10(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "ln": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "logn": - if (args.Length == 2) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + "'" + ((Symbol)args[1]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sqrt": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sqrt(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "abs": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Abs(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "acos": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Acos(((Symbol)args[0]).m_value) * 180 / DecimalMath.PI; - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "asin": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Asin(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "atan": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Atan(((Symbol)args[0]).m_value) * 180 / DecimalMath.PI; - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "exp": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Exp(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - default: - if (m_defaultFunctionEvaluation != null) - result = m_defaultFunctionEvaluation(name, args); - else - { - result.m_name = "Function: " + name + ", not found."; - result.m_type = Type.Error; - } - break; + switch (lowerName) + { + case "cos": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Cos(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sin": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sin(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "tan": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Tan(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cot": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + decimal sinVal = DecimalMath.Sin(v * angleFactor); + if (DecimalMath.Abs(sinVal) <= 1e-25m) + { + result.m_name = "Cot(x) bu noktada tanımsızdır (sin(x) = 0)."; + result.m_type = Type.Error; + } + else + { + result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal; + } + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cosh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Cosh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sinh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sinh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "tanh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Tanh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "log": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log10(v); + } + else if (args.Length == 2) + { + decimal v = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "ln": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "logn": + if (args.Length == 2) + { + decimal v = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sqrt": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sqrt(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cbrt": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = v < 0 ? -DecimalMath.Pow(-v, 1m / 3m) : DecimalMath.Pow(v, 1m / 3m); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "abs": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Abs(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "acos": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Acos(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "asin": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Asin(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "atan": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Atan(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "atan2": + if (args.Length == 2) + { + decimal y = ((Symbol)args[0]).m_value; + decimal x = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + y.ToString(CultureInfo.InvariantCulture) + "," + x.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Atan2(y, x) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: atan2(y, x)"; + result.m_type = Type.Error; + } + break; + case "exp": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Exp(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "max": + if (args.Length == 2) + { + decimal a = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_value = Math.Max(a, b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: max(a, b)"; + result.m_type = Type.Error; + } + break; + case "min": + if (args.Length == 2) + { + decimal a = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_value = Math.Min(a, b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: min(a, b)"; + result.m_type = Type.Error; + } + break; + case "floor": + if (args.Length == 1) + { + result.m_value = decimal.Floor(((Symbol)args[0]).m_value); + } + break; + case "ceil": + if (args.Length == 1) + { + result.m_value = decimal.Ceiling(((Symbol)args[0]).m_value); + } + break; + case "round": + if (args.Length == 1) + { + result.m_value = decimal.Round(((Symbol)args[0]).m_value); + } + break; + case "sign": + if (args.Length == 1) + { + result.m_value = DecimalMath.Sign(((Symbol)args[0]).m_value); + } + break; + default: + if (m_defaultFunctionEvaluation != null) + result = m_defaultFunctionEvaluation(name, args); + else + { + result.m_name = "Fonksiyon bulunamadı: " + name; + result.m_type = Type.Error; + } + break; + } + } + catch (Exception ex) + { + result.m_name = ex.Message; + result.m_type = Type.Error; } return result; } diff --git a/Assets/Scripts/Matrix.cs b/Assets/Scripts/Matrix.cs index 2c529e7..ab84f5e 100644 --- a/Assets/Scripts/Matrix.cs +++ b/Assets/Scripts/Matrix.cs @@ -1,10 +1,13 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; +using System.Globalization; +using DotNetMatrix; public class Matrix { + private static Random random = new Random(); + public static decimal[][] GenerateRandomMatrix(int rows, int columns, decimal min, decimal max) { decimal[][] res = new decimal[rows][]; @@ -13,8 +16,10 @@ public class Matrix res[i] = new decimal[columns]; for (int j = 0; j < columns; j++) { - decimal value = (decimal)UnityEngine.Random.Range((float)min, (float)max); - value = (decimal)System.Math.Round(value, 2); + double range = (double)(max - min); + double sample = random.NextDouble(); + double scaled = (sample * range) + (double)min; + decimal value = (decimal)System.Math.Round(scaled, 2); res[i][j] = value; } } @@ -23,6 +28,7 @@ public class Matrix public static decimal[][] Transpoze(decimal[][] _m) { + if (_m == null || _m.Length == 0) return new decimal[0][]; decimal[][] res = new decimal[_m[0].Length][]; for (int i = 0; i < _m[0].Length; i++) { @@ -40,156 +46,81 @@ public class Matrix public static decimal MatrixDeterminant(decimal[][] _m) { - if (_m.Length == _m[0].Length) + if (_m == null || _m.Length == 0) return 0; + if (_m.Length != _m[0].Length) { - int c = _m.Length; - if (c == 2) - { - return (decimal)Math.Round(_m[0][0] * _m[1][1] - _m[0][1] * _m[1][0], 5); - } - else if (c == 1) - { - return (decimal)Math.Round(_m[0][0], 5); - } - else if (c == 0) - { - Debug.LogError("Matrix is empty!"); - return 0; - } - else - { - decimal resDet = 0; - for (int i = 0; i < c; i++) - { - for (int j = 0; j < c; j++) - { - decimal[][] newM = new decimal[c - 1][]; - for (int k = 0; k < c - 1; k++) - { - newM[k] = new decimal[c - 1]; - } - - bool isAddedK = false, isAddedL = false; - int offsetK = 0, offsetL = 0; - - for (int k = 0; k < c; k++) - { - isAddedL = false; - offsetL = 0; - for (int l = 0; l < c; l++) - { - if (!(k == i || l == j)) - { - newM[k + offsetK][l + offsetL] = _m[k][l]; - } - else - { - if (!isAddedK && k == i) - { - offsetK = -1; - isAddedK = true; - } - if (!isAddedL && l == j) - { - offsetL = -1; - isAddedL = true; - } - } - } - } - - decimal cofactor = (decimal)Math.Pow(-1, 0 + j + 2) * MatrixDeterminant(newM); - resDet += cofactor * _m[0][j]; - } - } - return (decimal)Math.Round(resDet, 5); - } - } - else - { - Debug.LogError("This matrix is not a square matrix!"); - return 0; + throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır."); } + + int n = _m.Length; + if (n == 1) return _m[0][0]; + if (n == 2) return _m[0][0] * _m[1][1] - _m[0][1] * _m[1][0]; + + // Use O(n^3) LU Decomposition instead of O(n!) recursive Laplace expansion + GeneralMatrix gm = GeneralMatrix.ConstructWithCopy(_m); + return gm.Determinant(); } public static decimal[] SolveEquation(decimal[][] _m, decimal[] _v) { + if (_m == null || _v == null || _m.Length == 0) return new decimal[0]; int len = _m.Length; - decimal[] res = new decimal[len]; - decimal d0 = MatrixDeterminant(_m); - + GeneralMatrix A = GeneralMatrix.ConstructWithCopy(_m); + GeneralMatrix b = new GeneralMatrix(len, 1); for (int i = 0; i < len; i++) { - decimal[][] testMa = new decimal[len][]; - for (int j = 0; j < len; j++) - { - testMa[j] = new decimal[len]; - for (int k = 0; k < len; k++) - { - testMa[j][k] = _m[j][k]; - } - } - for (int j = 0; j < len; j++) - { - testMa[j][i] = _v[j]; - } - decimal di = MatrixDeterminant(testMa); - res[i] = (decimal)Math.Round(di / d0, 5); + b.Array[i][0] = _v[i]; } + GeneralMatrix x = A.Solve(b); + decimal[] res = new decimal[len]; + for (int i = 0; i < len; i++) + { + res[i] = x.Array[i][0]; + } return res; } public static decimal[][] ConvertLinearEquationsToMatrix(List equations, List variables) { - if (equations.Count == variables.Count) + if (equations == null || variables == null || equations.Count != variables.Count) return null; + + int n = equations.Count; + decimal[][] res = new decimal[n][]; + for (int i = 0; i < n; i++) { - decimal[][] res = new decimal[equations.Count][]; - for (int i = 0; i < res.Length; i++) + res[i] = new decimal[n]; + string eq = equations[i]; + if (eq.Contains("=")) { - res[i] = new decimal[equations.Count]; + string[] parts = eq.Split('='); + eq = parts[0] + "-(" + parts[1] + ")"; } - for (int i = 0; i < equations.Count; i++) + + // Use numerical evaluation to extract exact linear coefficients reliably: + // f(0, 0, ...) = c + // f(0, ..., x_k=1, ..., 0) - c = coeff_k + Dictionary zeroPts = new Dictionary(); + foreach (string v in variables) zeroPts[v] = 0m; + + decimal f0 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); + + for (int k = 0; k < n; k++) { - for (int j = 0; j < equations[i].Length; j++) - { - for (int k = 0; k < variables.Count; k++) - { - if (equations[i][j] == variables[k][0]) - { - string coeff = ""; - for (int l = j - 1; l >= 0; l--) - { - if (equations[i][l] != '*' && equations[i][l] != '+' && equations[i][l] != '-') - { - coeff += equations[i][l]; - } - if (equations[i][l] == '-') - { - coeff += '-'; - break; - } - if (equations[i][l] == '+') - { - break; - } - } - char[] charArray = coeff.ToCharArray(); - Array.Reverse(charArray); - coeff = new string(charArray); - res[i][k] = decimal.Parse(coeff); - } - } - } + string varName = variables[k]; + zeroPts[varName] = 1m; + decimal f1 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); + res[i][k] = f1 - f0; + zeroPts[varName] = 0m; } - return res; } - else return null; + return res; } public static decimal[][] MatrixMultiplication(decimal[][] _m1, decimal[][] _m2) { + if (_m1 == null || _m2 == null || _m1.Length == 0 || _m2.Length == 0) return null; if (_m1[0].Length == _m2.Length) { decimal[][] res = new decimal[_m1.Length][]; @@ -214,18 +145,20 @@ public class Matrix } else { - Debug.LogError("Matrices cannot be multiplied!"); - return null; + throw new ArgumentException("Birinci matrisin sütun sayısı ile ikinci matrisin satır sayısı eşit olmalıdır."); } } + public static decimal[][] MatrixMultiplication(decimal[][] _m, decimal _c) { - decimal[][] res = _m; + if (_m == null) return null; + decimal[][] res = new decimal[_m.Length][]; for (int i = 0; i < _m.Length; i++) { - for (int j = 0; j < _m[0].Length; j++) + res[i] = new decimal[_m[i].Length]; + for (int j = 0; j < _m[i].Length; j++) { - res[i][j] *= _c; + res[i][j] = _m[i][j] * _c; } } return res; @@ -233,47 +166,42 @@ public class Matrix public static decimal[] TurnListToVector(List _vec) { - decimal[] res = new decimal[_vec.Count]; - for (int i = 0; i < _vec.Count; i++) - { - res[i] = _vec[i]; - } - return res; + return _vec.ToArray(); } + public static decimal[][] TurnListToMatrix(List> _m) { decimal[][] res = new decimal[_m.Count][]; for (int i = 0; i < _m.Count; i++) { - res[i] = new decimal[_m[i].Count]; - for (int j = 0; j < _m[i].Count; j++) - { - res[i][j] = _m[i][j]; - } + res[i] = _m[i].ToArray(); } return res; } - public static string DebugMatrix(decimal[][] _m, string _sep = " ") + public static string DebugMatrix(decimal[][] _m, string _sep = "\t") { - string sum = ""; + if (_m == null || _m.Length == 0) return ""; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < _m.Length; i++) { - for (int j = 0; j < _m[0].Length; j++) + for (int j = 0; j < _m[i].Length; j++) { - sum += _m[i][j] + ((j == _m[0].Length - 1) ? "\n" : _sep); + sb.Append(_m[i][j].ToString("0.######", CultureInfo.InvariantCulture)); + sb.Append(j == _m[i].Length - 1 ? Environment.NewLine : _sep); } } - return sum; - } - public static string DebugVector(decimal[] _v, string _sep = " ") - { - string sum = ""; - for (int i = 0; i < _v.Length; i++) - { - sum += _v[i] + "\n"; - } - return sum; + return sb.ToString(); } + public static string DebugVector(decimal[] _v, string _sep = " ") + { + if (_v == null) return ""; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + for (int i = 0; i < _v.Length; i++) + { + sb.AppendLine(_v[i].ToString("0.######", CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } } diff --git a/Assets/Scripts/Matrix/CholeskyDecomposition.cs b/Assets/Scripts/Matrix/CholeskyDecomposition.cs index 382c612..d185d19 100644 --- a/Assets/Scripts/Matrix/CholeskyDecomposition.cs +++ b/Assets/Scripts/Matrix/CholeskyDecomposition.cs @@ -56,6 +56,7 @@ namespace DotNetMatrix // Main loop. for (int j = 0; j < n; j++) { + if (!isspd) break; decimal[] Lrowj = L[j]; decimal d = 0.0m; for (int k = 0; k < j; k++) @@ -66,13 +67,25 @@ namespace DotNetMatrix { s += Lrowk[i] * Lrowj[i]; } + if (L[k][k] <= 0.0m) + { + isspd = false; + break; + } Lrowj[k] = s = (A[j][k] - s) / L[k][k]; d = d + s * s; isspd = isspd & (A[k][j] == A[j][k]); } + if (!isspd) break; d = A[j][j] - d; isspd = isspd & (d > 0.0m); - L[j][j] = (decimal)Math.Sqrt(Math.Max((double)d, 0)); + if (!isspd || d <= 0.0m) + { + isspd = false; + L[j][j] = 0.0m; + break; + } + L[j][j] = DecimalMath.Sqrt(d); for (int k = j + 1; k < n; k++) { L[j][k] = 0.0m; @@ -171,4 +184,4 @@ namespace DotNetMatrix { } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Matrix/EigenvalueDecomposition.cs b/Assets/Scripts/Matrix/EigenvalueDecomposition.cs index e1263ab..3cf03a8 100644 --- a/Assets/Scripts/Matrix/EigenvalueDecomposition.cs +++ b/Assets/Scripts/Matrix/EigenvalueDecomposition.cs @@ -4,81 +4,25 @@ using System.Runtime.Serialization; namespace DotNetMatrix { - - /// Eigenvalues and eigenvectors of a real matrix. - /// If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is - /// diagonal and the eigenvector matrix V is orthogonal. - /// I.e. A = V.Multiply(D.Multiply(V.Transpose())) and - /// V.Multiply(V.Transpose()) equals the identity matrix. - /// If A is not symmetric, then the eigenvalue matrix D is block diagonal - /// with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, - /// lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The - /// columns of V represent the eigenvectors in the sense that A*V = V*D, - /// i.e. A.Multiply(V) equals V.Multiply(D). The matrix V may be badly - /// conditioned, or even singular, so the validity of the equation - /// A = V*D*Inverse(V) depends upon V.cond(). - /// - /// - [Serializable] public class EigenvalueDecomposition : System.Runtime.Serialization.ISerializable { - #region Class variables - - /// Row and column dimension (square matrix). - /// @serial matrix dimension. - /// private int n; - - /// Symmetry flag. - /// @serial internal symmetry flag. - /// private bool issymmetric; - - /// Arrays for internal storage of eigenvalues. - /// @serial internal storage of eigenvalues. - /// private decimal[] d, e; - - /// Array for internal storage of eigenvectors. - /// @serial internal storage of eigenvectors. - /// private decimal[][] V; - - /// Array for internal storage of nonsymmetric Hessenberg form. - /// @serial internal storage of nonsymmetric Hessenberg form. - /// private decimal[][] H; - - /// Working storage for nonsymmetric algorithm. - /// @serial working storage for nonsymmetric algorithm. - /// private decimal[] ort; - #endregion // Class variables - - #region Private Methods - - // Symmetric Householder reduction to tridiagonal form. - private void tred2() { - // This is derived from the Algol procedures tred2 by - // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for - // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutine in EISPACK. - for (int j = 0; j < n; j++) { d[j] = V[n - 1][j]; } - // Householder reduction to tridiagonal form. - for (int i = n - 1; i > 0; i--) { - // Scale to avoid under/overflow. - decimal scale = 0.0m; decimal h = 0.0m; for (int k = 0; k < i; k++) @@ -97,8 +41,6 @@ namespace DotNetMatrix } else { - // Generate Householder vector. - for (int k = 0; k < i; k++) { d[k] /= scale; @@ -118,8 +60,6 @@ namespace DotNetMatrix e[j] = 0.0m; } - // Apply similarity transformation to remaining columns. - for (int j = 0; j < i; j++) { f = d[j]; @@ -158,8 +98,6 @@ namespace DotNetMatrix d[i] = h; } - // Accumulate transformations. - for (int i = 0; i < n - 1; i++) { V[n - 1][i] = V[i][i]; @@ -198,15 +136,8 @@ namespace DotNetMatrix e[0] = 0.0m; } - // Symmetric tridiagonal QL algorithm. - private void tql2() { - // This is derived from the Algol procedures tql2, by - // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for - // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutine in EISPACK. - for (int i = 1; i < n; i++) { e[i - 1] = e[i]; @@ -215,11 +146,9 @@ namespace DotNetMatrix decimal f = 0.0m; decimal tst1 = 0.0m; - decimal eps = (decimal)DecimalMath.Pow(2.0m, - 52.0m); + decimal eps = DecimalMath.Pow(2.0m, -64.0m); for (int l = 0; l < n; l++) { - // Find small subdiagonal element - tst1 = System.Math.Max(tst1, System.Math.Abs(d[l]) + System.Math.Abs(e[l])); int m = l; while (m < n) @@ -231,18 +160,13 @@ namespace DotNetMatrix m++; } - // If m == l, d[l] is an eigenvalue, - // otherwise, iterate. - if (m > l) { int iter = 0; do { - iter = iter + 1; // (Could check iteration count here.) - - // Compute implicit shift - + iter = iter + 1; + if (iter > 120) break; decimal g = d[l]; decimal p = (d[l + 1] - g) / (2.0m * e[l]); decimal r = Maths.Hypot(p, 1.0m); @@ -260,8 +184,6 @@ namespace DotNetMatrix } f = f + h; - // Implicit QL transformation. - p = d[m]; decimal c = 1.0m; decimal c2 = c; @@ -283,8 +205,6 @@ namespace DotNetMatrix p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); - // Accumulate transformation. - for (int k = 0; k < n; k++) { h = V[k][i + 1]; @@ -295,8 +215,6 @@ namespace DotNetMatrix p = (- s) * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; - - // Check for convergence. } while (System.Math.Abs(e[l]) > eps * tst1); } @@ -304,8 +222,6 @@ namespace DotNetMatrix e[l] = 0.0m; } - // Sort eigenvalues and corresponding vectors. - for (int i = 0; i < n - 1; i++) { int k = i; @@ -332,23 +248,13 @@ namespace DotNetMatrix } } - // Nonsymmetric reduction to Hessenberg form. - private void orthes() { - // This is derived from the Algol procedures orthes and ortran, - // by Martin and Wilkinson, Handbook for Auto. Comp., - // Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutines in EISPACK. - int low = 0; int high = n - 1; for (int m = low + 1; m <= high - 1; m++) { - - // Scale column. - decimal scale = 0.0m; for (int i = m; i <= high; i++) { @@ -356,9 +262,6 @@ namespace DotNetMatrix } if (scale != 0.0m) { - - // Compute Householder transformation. - decimal h = 0.0m; for (int i = high; i >= m; i--) { @@ -373,9 +276,6 @@ namespace DotNetMatrix h = h - ort[m] * g; ort[m] = ort[m] - g; - // Apply Householder similarity transformation - // H = (I-u*u'/h)*H*(I-u*u')/h) - for (int j = m; j < n; j++) { decimal f = 0.0m; @@ -408,8 +308,6 @@ namespace DotNetMatrix } } - // Accumulate transformations (Algol's ortran). - for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) @@ -433,7 +331,6 @@ namespace DotNetMatrix { g += ort[i] * V[i][j]; } - // decimal division avoids possible underflow g = (g / ort[m]) / H[m][m - 1]; for (int i = m; i <= high; i++) { @@ -445,8 +342,6 @@ namespace DotNetMatrix } - // Complex scalar division. - [NonSerialized()] private decimal cdivr, cdivi; @@ -469,18 +364,8 @@ namespace DotNetMatrix } } - - // Nonsymmetric reduction from Hessenberg to real Schur form. - private void hqr2() { - // This is derived from the Algol procedure hqr2, - // by Martin and Wilkinson, Handbook for Auto. Comp., - // Vol.ii-Linear Algebra, and the corresponding - // Fortran subroutine in EISPACK. - - // Initialize - int nn = this.n; int n = nn - 1; int low = 0; @@ -489,8 +374,6 @@ namespace DotNetMatrix decimal exshift = 0.0m; decimal p = 0, q = 0, r = 0, s = 0, z = 0, t, w, x, y; - // Store roots isolated by balanc and compute matrix norm - decimal norm = 0.0m; for (int i = 0; i < nn; i++) { @@ -505,14 +388,11 @@ namespace DotNetMatrix } } - // Outer loop over eigenvalue index - int iter = 0; - while (n >= low) + int totalIter = 0; + while (n >= low && totalIter < 400) { - - // Look for single small sub-diagonal element - + totalIter++; int l = n; while (l > low) { @@ -528,9 +408,6 @@ namespace DotNetMatrix l--; } - // Check for convergence - // One root found - if (l == n) { H[n][n] = H[n][n] + exshift; @@ -538,8 +415,6 @@ namespace DotNetMatrix e[n] = 0.0m; n--; iter = 0; - - // Two roots found } else if (l == n - 1) { @@ -551,8 +426,6 @@ namespace DotNetMatrix H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; x = H[n][n]; - // Real pair - if (q >= 0) { if (p >= 0) @@ -579,8 +452,6 @@ namespace DotNetMatrix p = p / r; q = q / r; - // Row modification - for (int j = n - 1; j < nn; j++) { z = H[n - 1][j]; @@ -588,8 +459,6 @@ namespace DotNetMatrix H[n][j] = q * H[n][j] - p * z; } - // Column modification - for (int i = 0; i <= n; i++) { z = H[i][n - 1]; @@ -597,8 +466,6 @@ namespace DotNetMatrix H[i][n] = q * H[i][n] - p * z; } - // Accumulate transformations - for (int i = low; i <= high; i++) { z = V[i][n - 1]; @@ -606,7 +473,6 @@ namespace DotNetMatrix V[i][n] = q * V[i][n] - p * z; } - // Complex pair } else { @@ -618,13 +484,9 @@ namespace DotNetMatrix n = n - 2; iter = 0; - // No convergence yet } else { - - // Form shift - x = H[n][n]; y = 0.0m; w = 0.0m; @@ -634,8 +496,6 @@ namespace DotNetMatrix w = H[n][n - 1] * H[n - 1][n]; } - // Wilkinson's original ad hoc shift - if (iter == 10) { exshift += x; @@ -648,8 +508,6 @@ namespace DotNetMatrix w = (- 0.4375m) * s * s; } - // MATLAB's new ad hoc shift - if (iter == 30) { s = (y - x) / 2.0m; @@ -671,9 +529,7 @@ namespace DotNetMatrix } } - iter = iter + 1; // (Could check iteration count here.) - - // Look for two consecutive small sub-diagonal elements + iter = iter + 1; int m = n - 2; while (m >= l) @@ -708,8 +564,6 @@ namespace DotNetMatrix } } - // decimal QR step involving rows l:n and columns m:n - for (int k = m; k <= n - 1; k++) { bool notlast = (k != n - 1); @@ -752,8 +606,6 @@ namespace DotNetMatrix q = q / p; r = r / p; - // Row modification - for (int j = k; j < nn; j++) { p = H[k][j] + q * H[k + 1][j]; @@ -766,8 +618,6 @@ namespace DotNetMatrix H[k + 1][j] = H[k + 1][j] - p * y; } - // Column modification - for (int i = 0; i <= System.Math.Min(n, k + 3); i++) { p = x * H[i][k] + y * H[i][k + 1]; @@ -780,8 +630,6 @@ namespace DotNetMatrix H[i][k + 1] = H[i][k + 1] - p * q; } - // Accumulate transformations - for (int i = low; i <= high; i++) { p = x * V[i][k] + y * V[i][k + 1]; @@ -793,12 +641,10 @@ namespace DotNetMatrix V[i][k] = V[i][k] - p; V[i][k + 1] = V[i][k + 1] - p * q; } - } // (s != 0) - } // k loop - } // check convergence - } // while (n >= low) - - // Backsubstitute to find vectors of upper triangular form + } + } + } + } if (norm == 0.0m) { @@ -810,8 +656,6 @@ namespace DotNetMatrix p = d[n]; q = e[n]; - // Real vector - if (q == 0) { int l = n; @@ -842,8 +686,6 @@ namespace DotNetMatrix { H[i][n] = (- r) / (eps * norm); } - - // Solve real equations } else { @@ -862,10 +704,8 @@ namespace DotNetMatrix } } - // Overflow control - t = System.Math.Abs(H[i][n]); - if ((eps * t) * t > 1) + if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) { for (int j = i; j <= n; j++) { @@ -874,15 +714,10 @@ namespace DotNetMatrix } } } - - // Complex vector } else if (q < 0) { int l = n - 1; - - // Last vector component imaginary so matrix is triangular - if (System.Math.Abs(H[n][n - 1]) > System.Math.Abs(H[n - 1][n])) { H[n - 1][n - 1] = q / H[n][n - 1]; @@ -925,9 +760,6 @@ namespace DotNetMatrix } else { - - // Solve complex equations - x = H[i][i + 1]; y = H[i + 1][i]; vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; @@ -952,10 +784,8 @@ namespace DotNetMatrix } } - // Overflow control - t = System.Math.Max(System.Math.Abs(H[i][n - 1]), System.Math.Abs(H[i][n])); - if ((eps * t) * t > 1) + if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) { for (int j = i; j <= n; j++) { @@ -968,8 +798,6 @@ namespace DotNetMatrix } } - // Vectors of isolated roots - for (int i = 0; i < nn; i++) { if (i < low | i > high) @@ -981,8 +809,6 @@ namespace DotNetMatrix } } - // Back transformation to get eigenvectors of original matrix - for (int j = nn - 1; j >= low; j--) { for (int i = low; i <= high; i++) @@ -997,17 +823,6 @@ namespace DotNetMatrix } } - #endregion // Private Methods - - - #region Constructor - - /// Check for symmetry, then construct the eigenvalue decomposition - /// Square matrix - /// - /// Structure to access D and V. - /// - public EigenvalueDecomposition(GeneralMatrix Arg) { decimal[][] A = Arg.Array; @@ -1039,10 +854,7 @@ namespace DotNetMatrix } } - // Tridiagonalize. tred2(); - - // Diagonalize. tql2(); } else @@ -1062,20 +874,11 @@ namespace DotNetMatrix } } - // Reduce to Hessenberg form. orthes(); - - // Reduce Hessenberg to real Schur form. hqr2(); } } - #endregion // Constructor - - #region Public Properties - /// Return the real parts of the eigenvalues - /// real(diag(D)) - /// virtual public decimal[] RealEigenvalues { get @@ -1083,9 +886,6 @@ namespace DotNetMatrix return d; } } - /// Return the imaginary parts of the eigenvalues - /// imag(diag(D)) - /// virtual public decimal[] ImagEigenvalues { get @@ -1093,9 +893,6 @@ namespace DotNetMatrix return e; } } - /// Return the block diagonal eigenvalue matrix - /// D - /// virtual public GeneralMatrix D { get @@ -1121,23 +918,14 @@ namespace DotNetMatrix return X; } } - #endregion // Public Properties - - #region Public Methods - - /// Return the eigenvector matrix - /// V - /// public virtual GeneralMatrix GetV() { return new GeneralMatrix(V, n, n); } - #endregion // Public Methods - // A method called when serializing this class. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Matrix/GeneralMatrix.cs b/Assets/Scripts/Matrix/GeneralMatrix.cs index ed4d811..a026b32 100644 --- a/Assets/Scripts/Matrix/GeneralMatrix.cs +++ b/Assets/Scripts/Matrix/GeneralMatrix.cs @@ -3,16 +3,8 @@ using System.Runtime.Serialization; namespace DotNetMatrix { - #region Internal Maths utility internal class Maths { - /// - /// sqrt(a^2 + b^2) without under/overflow. - /// - /// - /// - /// - public static decimal Hypot(decimal a, decimal b) { decimal r; @@ -33,77 +25,12 @@ namespace DotNetMatrix return r; } } - #endregion // Internal Maths utility - - /// .NET GeneralMatrix class. - /// - /// The .NET GeneralMatrix Class provides the fundamental operations of numerical - /// linear algebra. Various constructors create Matrices from two dimensional - /// arrays of decimal precision decimaling point numbers. Various "gets" and - /// "sets" provide access to submatrices and matrix elements. Several methods - /// implement basic matrix arithmetic, including matrix addition and - /// multiplication, matrix norms, and element-by-element array operations. - /// Methods for reading and printing matrices are also included. All the - /// operations in this version of the GeneralMatrix Class involve real matrices. - /// Complex matrices may be handled in a future version. - /// - /// Five fundamental matrix decompositions, which consist of pairs or triples - /// of matrices, permutation vectors, and the like, produce results in five - /// decomposition classes. These decompositions are accessed by the GeneralMatrix - /// class to compute solutions of simultaneous linear equations, determinants, - /// inverses and other matrix functions. The five decompositions are: - ///

    - ///
  • Cholesky Decomposition of symmetric, positive definite matrices. - ///
  • LU Decomposition of rectangular matrices. - ///
  • QR Decomposition of rectangular matrices. - ///
  • Singular Value Decomposition of rectangular matrices. - ///
  • Eigenvalue Decomposition of both symmetric and nonsymmetric square matrices. - ///
- ///
- ///
Example of use:
- ///

- ///

Solve a linear system A x = b and compute the residual norm, ||b - A x||. - ///

-	/// decimal[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
-	/// GeneralMatrix A = new GeneralMatrix(vals);
-	/// GeneralMatrix b = GeneralMatrix.Random(3,1);
-	/// GeneralMatrix x = A.Solve(b);
-	/// GeneralMatrix r = A.Multiply(x).Subtract(b);
-	/// decimal rnorm = r.NormInf();
-	/// 
- ///
- ///
- /// - /// The MathWorks, Inc. and the National Institute of Standards and Technology. - /// - /// 5 August 1998 - /// [Serializable] public class GeneralMatrix : System.ICloneable, System.Runtime.Serialization.ISerializable, System.IDisposable { - #region Class variables - - /// Array for internal storage of elements. - /// @serial internal array storage. - /// private decimal[][] A; - - /// Row and column dimensions. - /// @serial row dimension. - /// @serial column dimension. - /// private int m, n; - - #endregion // Class variables - - #region Constructors - - /// Construct an m-by-n matrix of zeros. - /// Number of rows. - /// - /// Number of colums. - /// public GeneralMatrix(int m, int n) { @@ -116,14 +43,6 @@ namespace DotNetMatrix } } - /// Construct an m-by-n constant matrix. - /// Number of rows. - /// - /// Number of colums. - /// - /// Fill the matrix with this scalar value. - /// - public GeneralMatrix(int m, int n, decimal s) { this.m = m; @@ -132,9 +51,6 @@ namespace DotNetMatrix for (int i = 0; i < m; i++) { A[i] = new decimal[n]; - } - for (int i = 0; i < m; i++) - { for (int j = 0; j < n; j++) { A[i][j] = s; @@ -142,14 +58,6 @@ namespace DotNetMatrix } } - /// Construct a matrix from a 2-D array. - /// Two-dimensional array of decimals. - /// - /// All rows must have the same length - /// - /// - /// - public GeneralMatrix(decimal[][] A) { m = A.Length; @@ -164,14 +72,6 @@ namespace DotNetMatrix this.A = A; } - /// Construct a matrix quickly without checking arguments. - /// Two-dimensional array of decimals. - /// - /// Number of rows. - /// - /// Number of colums. - /// - public GeneralMatrix(decimal[][] A, int m, int n) { this.A = A; @@ -179,14 +79,6 @@ namespace DotNetMatrix this.n = n; } - /// Construct a matrix from a one-dimensional packed array - /// One-dimensional array of decimals, packed by columns (ala Fortran). - /// - /// Number of rows. - /// - /// Array length must be a multiple of m. - /// - public GeneralMatrix(decimal[] vals, int m) { this.m = m; @@ -199,33 +91,22 @@ namespace DotNetMatrix for (int i = 0; i < m; i++) { A[i] = new decimal[n]; - } - for (int i = 0; i < m; i++) - { for (int j = 0; j < n; j++) { A[i][j] = vals[i + j * m]; } } } - #endregion // Constructors - - #region Public Properties - /// Access the internal two-dimensional array. - /// Pointer to the two-dimensional array of matrix elements. - /// - virtual public decimal[][] Array - { + public virtual decimal[][] Array + { get { return A; } } - /// Copy the internal two-dimensional array. - /// Two-dimensional array copy of matrix elements. - /// - virtual public decimal[][] ArrayCopy + + public virtual decimal[][] ArrayCopy { get { @@ -233,9 +114,6 @@ namespace DotNetMatrix for (int i = 0; i < m; i++) { C[i] = new decimal[n]; - } - for (int i = 0; i < m; i++) - { for (int j = 0; j < n; j++) { C[i][j] = A[i][j]; @@ -243,12 +121,9 @@ namespace DotNetMatrix } return C; } - } - /// Make a one-dimensional column packed copy of the internal array. - /// Matrix elements packed in a one-dimensional array by columns. - /// - virtual public decimal[] ColumnPackedCopy + + public virtual decimal[] ColumnPackedCopy { get { @@ -262,13 +137,9 @@ namespace DotNetMatrix } return vals; } - } - /// Make a one-dimensional row packed copy of the internal array. - /// Matrix elements packed in a one-dimensional array by rows. - /// - virtual public decimal[] RowPackedCopy + public virtual decimal[] RowPackedCopy { get { @@ -284,10 +155,7 @@ namespace DotNetMatrix } } - /// Get row dimension. - /// m, the number of rows. - /// - virtual public int RowDimension + public virtual int RowDimension { get { @@ -295,27 +163,15 @@ namespace DotNetMatrix } } - /// Get column dimension. - /// n, the number of columns. - /// - virtual public int ColumnDimension + public virtual int ColumnDimension { get { return n; } } - #endregion // Public Properties - #region Public Methods - - /// Construct a matrix from a copy of a 2-D array. - /// Two-dimensional array of decimals. - /// - /// All rows must have the same length - /// - - public static GeneralMatrix Create(decimal[][] A) + public static GeneralMatrix ConstructWithCopy(decimal[][] A) { int m = A.Length; int n = A[0].Length; @@ -335,8 +191,6 @@ namespace DotNetMatrix return X; } - /// Make a deep copy of a matrix - public virtual GeneralMatrix Copy() { GeneralMatrix X = new GeneralMatrix(m, n); @@ -351,35 +205,11 @@ namespace DotNetMatrix return X; } - /// Get a single element. - /// Row index. - /// - /// Column index. - /// - /// A(i,j) - /// - /// - /// - public virtual decimal GetElement(int i, int j) { return A[i][j]; } - /// Get a submatrix. - /// Initial row index - /// - /// Final row index - /// - /// Initial column index - /// - /// Final column index - /// - /// A(i0:i1,j0:j1) - /// - /// Submatrix indices - /// - public virtual GeneralMatrix GetMatrix(int i0, int i1, int j0, int j1) { GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, j1 - j0 + 1); @@ -401,16 +231,6 @@ namespace DotNetMatrix return X; } - /// Get a submatrix. - /// Array of row indices. - /// - /// Array of column indices. - /// - /// A(r(:),c(:)) - /// - /// Submatrix indices - /// - public virtual GeneralMatrix GetMatrix(int[] r, int[] c) { GeneralMatrix X = new GeneralMatrix(r.Length, c.Length); @@ -432,18 +252,6 @@ namespace DotNetMatrix return X; } - /// Get a submatrix. - /// Initial row index - /// - /// Final row index - /// - /// Array of column indices. - /// - /// A(i0:i1,c(:)) - /// - /// Submatrix indices - /// - public virtual GeneralMatrix GetMatrix(int i0, int i1, int[] c) { GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, c.Length); @@ -465,18 +273,6 @@ namespace DotNetMatrix return X; } - /// Get a submatrix. - /// Array of row indices. - /// - /// Initial column index - /// - /// Final column index - /// - /// A(r(:),j0:j1) - /// - /// Submatrix indices - /// - public virtual GeneralMatrix GetMatrix(int[] r, int j0, int j1) { GeneralMatrix X = new GeneralMatrix(r.Length, j1 - j0 + 1); @@ -498,35 +294,11 @@ namespace DotNetMatrix return X; } - /// Set a single element. - /// Row index. - /// - /// Column index. - /// - /// A(i,j). - /// - /// - /// - public virtual void SetElement(int i, int j, decimal s) { A[i][j] = s; } - /// Set a submatrix. - /// Initial row index - /// - /// Final row index - /// - /// Initial column index - /// - /// Final column index - /// - /// A(i0:i1,j0:j1) - /// - /// Submatrix indices - /// - public virtual void SetMatrix(int i0, int i1, int j0, int j1, GeneralMatrix X) { try @@ -545,16 +317,6 @@ namespace DotNetMatrix } } - /// Set a submatrix. - /// Array of row indices. - /// - /// Array of column indices. - /// - /// A(r(:),c(:)) - /// - /// Submatrix indices - /// - public virtual void SetMatrix(int[] r, int[] c, GeneralMatrix X) { try @@ -573,18 +335,6 @@ namespace DotNetMatrix } } - /// Set a submatrix. - /// Array of row indices. - /// - /// Initial column index - /// - /// Final column index - /// - /// A(r(:),j0:j1) - /// - /// Submatrix indices - /// - public virtual void SetMatrix(int[] r, int j0, int j1, GeneralMatrix X) { try @@ -603,18 +353,6 @@ namespace DotNetMatrix } } - /// Set a submatrix. - /// Initial row index - /// - /// Final row index - /// - /// Array of column indices. - /// - /// A(i0:i1,c(:)) - /// - /// Submatrix indices - /// - public virtual void SetMatrix(int i0, int i1, int[] c, GeneralMatrix X) { try @@ -633,10 +371,6 @@ namespace DotNetMatrix } } - /// Matrix transpose. - /// A' - /// - public virtual GeneralMatrix Transpose() { GeneralMatrix X = new GeneralMatrix(n, m); @@ -651,10 +385,6 @@ namespace DotNetMatrix return X; } - /// One norm - /// maximum column sum. - /// - public virtual decimal Norm1() { decimal f = 0; @@ -670,19 +400,6 @@ namespace DotNetMatrix return f; } - /// Two norm - /// maximum singular value. - /// - - public virtual decimal Norm2() - { - return (new SingularValueDecomposition(this).Norm2()); - } - - /// Infinity norm - /// maximum row sum. - /// - public virtual decimal NormInf() { decimal f = 0; @@ -697,11 +414,7 @@ namespace DotNetMatrix } return f; } - - /// Frobenius norm - /// sqrt of sum of squares of all elements. - /// - + public virtual decimal NormF() { decimal f = 0; @@ -715,10 +428,6 @@ namespace DotNetMatrix return f; } - /// Unary minus - /// -A - /// - public virtual GeneralMatrix UnaryMinus() { GeneralMatrix X = new GeneralMatrix(m, n); @@ -727,18 +436,12 @@ namespace DotNetMatrix { for (int j = 0; j < n; j++) { - C[i][j] = -A[i][j]; + C[i][j] = - A[i][j]; } } return X; } - /// C = A + B - /// another matrix - /// - /// A + B - /// - public virtual GeneralMatrix Add(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -754,12 +457,6 @@ namespace DotNetMatrix return X; } - /// A = A + B - /// another matrix - /// - /// A + B - /// - public virtual GeneralMatrix AddEquals(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -773,12 +470,6 @@ namespace DotNetMatrix return this; } - /// C = A - B - /// another matrix - /// - /// A - B - /// - public virtual GeneralMatrix Subtract(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -794,12 +485,6 @@ namespace DotNetMatrix return X; } - /// A = A - B - /// another matrix - /// - /// A - B - /// - public virtual GeneralMatrix SubtractEquals(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -813,12 +498,6 @@ namespace DotNetMatrix return this; } - /// Element-by-element multiplication, C = A.*B - /// another matrix - /// - /// A.*B - /// - public virtual GeneralMatrix ArrayMultiply(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -834,12 +513,6 @@ namespace DotNetMatrix return X; } - /// Element-by-element multiplication in place, A = A.*B - /// another matrix - /// - /// A.*B - /// - public virtual GeneralMatrix ArrayMultiplyEquals(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -853,12 +526,6 @@ namespace DotNetMatrix return this; } - /// Element-by-element right division, C = A./B - /// another matrix - /// - /// A./B - /// - public virtual GeneralMatrix ArrayRightDivide(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -874,12 +541,6 @@ namespace DotNetMatrix return X; } - /// Element-by-element right division in place, A = A./B - /// another matrix - /// - /// A./B - /// - public virtual GeneralMatrix ArrayRightDivideEquals(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -893,12 +554,6 @@ namespace DotNetMatrix return this; } - /// Element-by-element left division, C = A.\B - /// another matrix - /// - /// A.\B - /// - public virtual GeneralMatrix ArrayLeftDivide(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -914,12 +569,6 @@ namespace DotNetMatrix return X; } - /// Element-by-element left division in place, A = A.\B - /// another matrix - /// - /// A.\B - /// - public virtual GeneralMatrix ArrayLeftDivideEquals(GeneralMatrix B) { CheckMatrixDimensions(B); @@ -933,12 +582,6 @@ namespace DotNetMatrix return this; } - /// Multiply a matrix by a scalar, C = s*A - /// scalar - /// - /// s*A - /// - public virtual GeneralMatrix Multiply(decimal s) { GeneralMatrix X = new GeneralMatrix(m, n); @@ -953,12 +596,6 @@ namespace DotNetMatrix return X; } - /// Multiply a matrix by a scalar in place, A = s*A - /// scalar - /// - /// replace A by s*A - /// - public virtual GeneralMatrix MultiplyEquals(decimal s) { for (int i = 0; i < m; i++) @@ -971,14 +608,6 @@ namespace DotNetMatrix return this; } - /// Linear algebraic matrix multiplication, A * B - /// another matrix - /// - /// Matrix product, A * B - /// - /// Matrix inner dimensions must agree. - /// - public virtual GeneralMatrix Multiply(GeneralMatrix B) { if (B.m != n) @@ -1008,160 +637,76 @@ namespace DotNetMatrix return X; } - #region Operator Overloading - - /// - /// Addition of matrices - /// - /// - /// - /// public static GeneralMatrix operator +(GeneralMatrix m1, GeneralMatrix m2) { return m1.Add(m2); } - - /// - /// Subtraction of matrices - /// - /// - /// - /// + public static GeneralMatrix operator -(GeneralMatrix m1, GeneralMatrix m2) { return m1.Subtract(m2); } - - /// - /// Multiplication of matrices - /// - /// - /// - /// + public static GeneralMatrix operator *(GeneralMatrix m1, GeneralMatrix m2) { return m1.Multiply(m2); } - - #endregion //Operator Overloading - - /// LU Decomposition - /// LUDecomposition - /// - /// - /// public virtual LUDecomposition LUD() { return new LUDecomposition(this); } - /// QR Decomposition - /// QRDecomposition - /// - /// - /// - public virtual QRDecomposition QRD() { return new QRDecomposition(this); } - /// Cholesky Decomposition - /// CholeskyDecomposition - /// - /// - /// - public virtual CholeskyDecomposition chol() { return new CholeskyDecomposition(this); } - /// Singular Value Decomposition - /// SingularValueDecomposition - /// - /// - /// - public virtual SingularValueDecomposition SVD() { return new SingularValueDecomposition(this); } - /// Eigenvalue Decomposition - /// EigenvalueDecomposition - /// - /// - /// - public virtual EigenvalueDecomposition Eigen() { return new EigenvalueDecomposition(this); } - /// Solve A*X = B - /// right hand side - /// - /// solution if A is square, least squares solution otherwise - /// - public virtual GeneralMatrix Solve(GeneralMatrix B) { return (m == n ? (new LUDecomposition(this)).Solve(B):(new QRDecomposition(this)).Solve(B)); } - /// Solve X*A = B, which is also A'*X' = B' - /// right hand side - /// - /// solution if A is square, least squares solution otherwise. - /// - public virtual GeneralMatrix SolveTranspose(GeneralMatrix B) { return Transpose().Solve(B.Transpose()); } - /// Matrix inverse or pseudoinverse - /// inverse(A) if A is square, pseudoinverse otherwise. - /// - public virtual GeneralMatrix Inverse() { return Solve(Identity(m, m)); } - /// GeneralMatrix determinant - /// determinant - /// - public virtual decimal Determinant() { return new LUDecomposition(this).Determinant(); } - /// GeneralMatrix rank - /// effective numerical rank, obtained from SVD. - /// - public virtual int Rank() { return new SingularValueDecomposition(this).Rank(); } - /// Matrix condition (2 norm) - /// ratio of largest to smallest singular value. - /// - public virtual decimal Condition() { return new SingularValueDecomposition(this).Condition(); } - /// Matrix trace. - /// sum of the diagonal elements. - /// - public virtual decimal Trace() { decimal t = 0; @@ -1172,38 +717,6 @@ namespace DotNetMatrix return t; } - /// Generate matrix with random elements - /// Number of rows. - /// - /// Number of colums. - /// - /// An m-by-n matrix with uniformly distributed random elements. - /// - - /*public static GeneralMatrix Random(int m, int n) - { - System.Random random = new System.Random(); - - GeneralMatrix A = new GeneralMatrix(m, n); - decimal[][] X = A.Array; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { - X[i][j] = random.Nextdecimal(); - } - } - return A; - }*/ - - /// Generate identity matrix - /// Number of rows. - /// - /// Number of colums. - /// - /// An m-by-n matrix with ones on the diagonal and zeros elsewhere. - /// - public static GeneralMatrix Identity(int m, int n) { GeneralMatrix A = new GeneralMatrix(m, n); @@ -1218,12 +731,6 @@ namespace DotNetMatrix return A; } - #endregion // Public Methods - - #region Private Methods - - /// Check if size(A) == size(B) * - private void CheckMatrixDimensions(GeneralMatrix B) { if (B.m != m || B.n != n) @@ -1231,67 +738,30 @@ namespace DotNetMatrix throw new System.ArgumentException("GeneralMatrix dimensions must agree."); } } - #endregion // Private Methods - #region Implement IDisposable - /// - /// Do not make this method virtual. - /// A derived class should not be able to override this method. - /// public void Dispose() { Dispose(true); } - /// - /// Dispose(bool disposing) executes in two distinct scenarios. - /// If disposing equals true, the method has been called directly - /// or indirectly by a user's code. Managed and unmanaged resources - /// can be disposed. - /// If disposing equals false, the method has been called by the - /// runtime from inside the finalizer and you should not reference - /// other objects. Only unmanaged resources can be disposed. - /// - /// private void Dispose(bool disposing) { - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SupressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. if (disposing) GC.SuppressFinalize(this); } - /// - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// ~GeneralMatrix() { - // Do not re-create Dispose clean-up code here. - // Calling Dispose(false) is optimal in terms of - // readability and maintainability. Dispose(false); } - #endregion // Implement IDisposable - /// Clone the GeneralMatrix object. public System.Object Clone() { return this.Copy(); } - /// - /// A method called when serializing this class - /// - /// - /// void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Matrix/LUDecomposition.cs b/Assets/Scripts/Matrix/LUDecomposition.cs index 5b97321..a30d86f 100644 --- a/Assets/Scripts/Matrix/LUDecomposition.cs +++ b/Assets/Scripts/Matrix/LUDecomposition.cs @@ -319,4 +319,4 @@ namespace DotNetMatrix { } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Matrix/QRDecomposition.cs b/Assets/Scripts/Matrix/QRDecomposition.cs index c6347c7..8702b0f 100644 --- a/Assets/Scripts/Matrix/QRDecomposition.cs +++ b/Assets/Scripts/Matrix/QRDecomposition.cs @@ -284,4 +284,4 @@ namespace DotNetMatrix { } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Matrix/SingularValueDecomposition.cs b/Assets/Scripts/Matrix/SingularValueDecomposition.cs index 27e12d3..206d5f6 100644 --- a/Assets/Scripts/Matrix/SingularValueDecomposition.cs +++ b/Assets/Scripts/Matrix/SingularValueDecomposition.cs @@ -3,60 +3,28 @@ using System.Runtime.Serialization; namespace DotNetMatrix { - - /// Singular Value Decomposition. - ///

- /// For an m-by-n matrix A with m >= n, the singular value decomposition is - /// an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and - /// an n-by-n orthogonal matrix V so that A = U*S*V'. - ///

- /// The singular values, sigma[k] = S[k][k], are ordered so that - /// sigma[0] >= sigma[1] >= ... >= sigma[n-1]. - ///

- /// The singular value decompostion always exists, so the constructor will - /// never fail. The matrix condition number and the effective numerical - /// rank can be computed from this decomposition. - ///

- [Serializable] public class SingularValueDecomposition : System.Runtime.Serialization.ISerializable { - #region Class variables - - /// Arrays for internal storage of U and V. - /// @serial internal storage of U. - /// @serial internal storage of V. - /// private decimal[][] U, V; - - /// Array for internal storage of singular values. - /// @serial internal storage of singular values. - /// private decimal[] s; - - /// Row and column dimensions. - /// @serial row dimension. - /// @serial column dimension. - /// private int m, n; - - #endregion //Class variables - - #region Constructor - - /// Construct the singular value decomposition - /// Rectangular matrix - /// - /// Structure to access U, S and V. - /// public SingularValueDecomposition(GeneralMatrix Arg) { - // Derived from LINPACK code. - // Initialize. - decimal[][] A = Arg.ArrayCopy; m = Arg.RowDimension; n = Arg.ColumnDimension; + + if (m < n) + { + SingularValueDecomposition svdTrans = new SingularValueDecomposition(Arg.Transpose()); + s = (decimal[])svdTrans.s.Clone(); + U = svdTrans.V; + V = svdTrans.U; + return; + } + + decimal[][] A = Arg.ArrayCopy; int nu = System.Math.Min(m, n); s = new decimal[System.Math.Min(m + 1, n)]; U = new decimal[m][]; @@ -74,19 +42,12 @@ namespace DotNetMatrix bool wantu = true; bool wantv = true; - // Reduce A to bidiagonal form, storing the diagonal elements - // in s and the super-diagonal elements in e. - int nct = System.Math.Min(m - 1, n); int nrt = System.Math.Max(0, System.Math.Min(n - 2, m)); for (int k = 0; k < System.Math.Max(nct, nrt); k++) { if (k < nct) { - - // Compute the transformation for the k-th column and - // place the k-th diagonal in s[k]. - // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { @@ -110,9 +71,6 @@ namespace DotNetMatrix { if ((k < nct) & (s[k] != 0.0m)) { - - // Apply the transformation. - decimal t = 0; for (int i = k; i < m; i++) { @@ -124,18 +82,10 @@ namespace DotNetMatrix A[i][j] += t * A[i][k]; } } - - // Place the k-th row of A into e for the - // subsequent calculation of the row transformation. - e[j] = A[k][j]; } if (wantu & (k < nct)) { - - // Place the transformation in U for subsequent back - // multiplication. - for (int i = k; i < m; i++) { U[i][k] = A[i][k]; @@ -143,10 +93,6 @@ namespace DotNetMatrix } if (k < nrt) { - - // Compute the k-th row transformation and place the - // k-th super-diagonal in e[k]. - // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k + 1; i < n; i++) { @@ -167,9 +113,6 @@ namespace DotNetMatrix e[k] = - e[k]; if ((k + 1 < m) & (e[k] != 0.0m)) { - - // Apply the transformation. - for (int i = k + 1; i < m; i++) { work[i] = 0.0m; @@ -192,10 +135,6 @@ namespace DotNetMatrix } if (wantv) { - - // Place the transformation in V for subsequent - // back multiplication. - for (int i = k + 1; i < n; i++) { V[i][k] = e[i]; @@ -204,8 +143,6 @@ namespace DotNetMatrix } } - // Set up the final bidiagonal matrix or order p. - int p = System.Math.Min(n, m + 1); if (nct < n) { @@ -221,8 +158,6 @@ namespace DotNetMatrix } e[p - 1] = 0.0m; - // If required, generate U. - if (wantu) { for (int j = nct; j < nu; j++) @@ -271,8 +206,6 @@ namespace DotNetMatrix } } - // If required, generate V. - if (wantv) { for (int k = n - 1; k >= 0; k--) @@ -301,27 +234,12 @@ namespace DotNetMatrix } } - // Main iteration loop for the singular values. - int pp = p - 1; int iter = 0; - decimal eps = (decimal)Math.Pow(2.0f, - 52.0f); - while (p > 0) + decimal eps = DecimalMath.Pow(2.0m, -64.0m); + while (p > 0 && iter < 150) { int k, kase; - - // Here is where a test for too many iterations would go. - - // This section of the program inspects for - // negligible elements in the s and e arrays. On - // completion the variables kase and k are set as follows. - - // kase = 1 if s(p) and e[k-1] are negligible and k

= - 1; k--) { if (k == - 1) @@ -370,13 +288,8 @@ namespace DotNetMatrix } k++; - // Perform the task indicated by kase. - switch (kase) { - - - // Deflate negligible s(p). case 1: { decimal f = e[p - 2]; @@ -404,10 +317,6 @@ namespace DotNetMatrix } } break; - - // Split at negligible s(k). - - case 2: { decimal f = e[k - 1]; @@ -432,14 +341,8 @@ namespace DotNetMatrix } } break; - - // Perform one qr step. - - case 3: { - // Calculate the shift. - decimal scale = System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Abs(s[p - 1]), System.Math.Abs(s[p - 2])), System.Math.Abs(e[p - 2])), System.Math.Abs(s[k])), System.Math.Abs(e[k])); decimal sp = s[p - 1] / scale; decimal spm1 = s[p - 2] / scale; @@ -461,8 +364,6 @@ namespace DotNetMatrix decimal f = (sk + sp) * (sk - sp) + shift; decimal g = sk * ek; - // Chase zeros. - for (int j = k; j < p - 1; j++) { decimal t = Maths.Hypot(f, g); @@ -507,14 +408,8 @@ namespace DotNetMatrix iter = iter + 1; } break; - - // Convergence. - - case 4: { - // Make the singular values positive. - if (s[k] <= 0.0m) { s[k] = (s[k] < 0.0m?- s[k]:0.0m); @@ -526,9 +421,6 @@ namespace DotNetMatrix } } } - - // Order the singular values. - while (k < pp) { if (s[k] >= s[k + 1]) @@ -561,12 +453,7 @@ namespace DotNetMatrix } } } - #endregion //Constructor - #region Public Properties - ///

Return the one-dimensional array of singular values - /// diagonal of S. - /// virtual public decimal[] SingularValues { get @@ -575,18 +462,16 @@ namespace DotNetMatrix } } - /// Return the diagonal matrix of singular values - /// S - /// virtual public GeneralMatrix S { get { - GeneralMatrix X = new GeneralMatrix(n, n); + int nu = System.Math.Min(m, n); + GeneralMatrix X = new GeneralMatrix(nu, nu); decimal[][] S = X.Array; - for (int i = 0; i < n; i++) + for (int i = 0; i < nu; i++) { - for (int j = 0; j < n; j++) + for (int j = 0; j < nu; j++) { S[i][j] = 0.0m; } @@ -595,50 +480,28 @@ namespace DotNetMatrix return X; } } - #endregion // Public Properties - - #region Public Methods - - /// Return the left singular vectors - /// U - /// public virtual GeneralMatrix GetU() { - return new GeneralMatrix(U, m, System.Math.Min(m + 1, n)); + return new GeneralMatrix(U, m, System.Math.Min(m, n)); } - /// Return the right singular vectors - /// V - /// - public virtual GeneralMatrix GetV() { - return new GeneralMatrix(V, n, n); + return new GeneralMatrix(V, n, System.Math.Min(m, n)); } - /// Two norm - /// max(S) - /// - public virtual decimal Norm2() { return s[0]; } - /// Two norm condition number - /// max(S)/min(S) - /// - public virtual decimal Condition() { - return s[0] / s[System.Math.Min(m, n) - 1]; + decimal minS = s[System.Math.Min(m, n) - 1]; + return minS != 0m ? s[0] / minS : decimal.MaxValue; } - /// Effective numerical matrix rank - /// Number of nonnegligible singular values. - /// - public virtual int Rank() { decimal eps = (decimal)System.Math.Pow(2.0f, - 52.0f); @@ -653,11 +516,9 @@ namespace DotNetMatrix } return r; } - #endregion //Public Methods - // A method called when serializing this class. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/NumericalMethods.cs b/Assets/Scripts/NumericalMethods.cs index a87922b..ec2bacd 100644 --- a/Assets/Scripts/NumericalMethods.cs +++ b/Assets/Scripts/NumericalMethods.cs @@ -1,442 +1,482 @@ -using DotNetMatrix; +using DotNetMatrix; +using System; using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Text; -using UnityEngine; +using System.Text.RegularExpressions; public class NumericalMethods { - #region GaussSeidal Yap Burayı - /*public static List Method_GaussSeidal(List _eq, Dictionary initialValues, int iterationCount) + public static string NormalizeEquation(string eq) { - //yakınsama şartı (3x3 matris için) -> |a11|>|a12|+|a13| && |a22|>|a21|+|a23| && |a33|>|a31|+|a32| - - bool convergence = true; - List dominantTerms = new List(); - for (int i = 0; i < _eq.Count; i++) + if (string.IsNullOrWhiteSpace(eq)) return ""; + eq = eq.Trim(); + if (eq.Contains("=")) { - int currentDominant = -1; - bool dominantFound = false; - for (int j = 0; j < _eq.Count; j++) + string[] parts = eq.Split('='); + if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[1])) { - decimal sum0 = 0; - - for (int k = 0; k < _eq.Count; k++) - { - if (k != j) - { - sum0 += Mathf.Abs(_eq[i].Coefficients[k]); - } - } - - if (Mathf.Abs(_eq[i].Coefficients[j]) > sum0) - { - currentDominant = j; - dominantFound = true; - break; - } - } - - if (dominantFound) - { - dominantTerms.Add(currentDominant); - } - else - { - dominantTerms.Add(-1); + return "(" + parts[0] + ")-(" + parts[1] + ")"; } } + return eq; + } - for (int i = 0; i < dominantTerms.Count && convergence; i++) + public static Function CompileFunction(string eq) + { + string norm = NormalizeEquation(eq); + Function f = new Function(); + f.Parse(norm); + if (f.Error) { - for (int j = 0; j < dominantTerms.Count; j++) - { - if (i != j) - { - if (dominantTerms[i] == dominantTerms[j]) - { - convergence = false; - break; - } - } - } + throw new ArgumentException("Denklem ayrıştırma hatası: " + f.ErrorDescription); } + f.Infix2Postfix(); + return f; + } - if (convergence == false) + public static decimal EvaluateCompiled(Function f, string variable, decimal point) + { + f.SetVariable(variable, point); + f.EvaluatePostfix(); + if (f.Error) { - Debug.LogError("This matris cannot be solved with Gauss-Seidal Method!"); - return new List(); + throw new ArithmeticException(f.ErrorDescription); } - else + return f.Result; + } + + public static decimal EvaluateCompiledMultiVar(Function f, Dictionary points) + { + f.SetVariables(points); + f.EvaluatePostfix(); + if (f.Error) { - List answers = initialValues; - for (int i = 0; i < iterationCount; i++) - { - for (int j = 0; j < _eq.Count; j++) - { - decimal sum = _eq[j].Constant + _eq[j].Coefficients[j] * answers[j]; - for (int k = 0; k < _eq.Count; k++) - { - sum += -_eq[j].Coefficients[k] * answers[k]; - } - answers[j] = sum / _eq[j].Coefficients[j]; - } - } - string ansdeb = ""; - for (int i = 0; i < answers.Count; i++) - { - ansdeb += answers[i] + ((i == answers.Count - 1) ? "" : ", "); - } - Debug.Log(ansdeb); - - return answers; + throw new ArithmeticException(f.ErrorDescription); } - }*/ - #endregion - + return f.Result; + } public static decimal Method_EvaluateFunction(string eq, string variable, decimal point) { - string newEq = eq; - - newEq = newEq.Replace(variable, point.ToString(/*new CultureInfo("en-US")*/)); - - Function f = new Function(); - f.Parse(newEq); - f.Infix2Postfix(); - f.EvaluatePostfix(); - return f.m_result; + Function f = CompileFunction(eq); + return EvaluateCompiled(f, variable, point); } + public static decimal MethodMultiVar_EvaluateFunction(string eq, Dictionary points) { - string newEq = eq; - foreach (KeyValuePair pt in points) - { - newEq = newEq.Replace(pt.Key, pt.Value.ToString(/*new CultureInfo("en-US")*/)); - } - //Debug.Log(newEq); - - Function f = new Function(); - f.Parse(newEq); - f.Infix2Postfix(); - f.EvaluatePostfix(); - //Debug.Log(f.ErrorDescription); - //Debug.Log(Math.Round(f.m_result, 5)); - return f.m_result; - + Function f = CompileFunction(eq); + return EvaluateCompiledMultiVar(f, points); } - - public static Dictionary MethodMultiVar_SolveEquationSystem(List eqs, Dictionary initPoints, int iterationCount = 5, decimal h = 0.001m) + /// + /// Solves a nonlinear or linear system of equations using Multivariable Newton-Raphson with analytical/numerical Jacobian + /// and returns step-by-step convergence logs as well as the final solution dictionary. + /// + public static Dictionary MethodMultiVar_SolveEquationSystem( + List eqs, + Dictionary initPoints, + int iterationCount = 50, + decimal h = 0.0001m) { - Dictionary dynamicPoints = initPoints; - for (int itC = 0; itC < iterationCount; itC++) - { - List linearizedEqs = new List(), variablesStr = new List(); - List leftVector = new List(); - for (int i = 0; i < eqs.Count; i++) - { - string le = MethodMultiVar_TaylorSeries(eqs[i], 1, dynamicPoints, h); + var logs = new List(); + return SolveEquationSystemWithLogs(eqs, initPoints, iterationCount, out logs, h); + } - int charCount = 0; - for (int j = 0; j < le.Length; j++) + public static Dictionary SolveEquationSystemWithLogs( + List eqs, + Dictionary initPoints, + int iterationCount, + out List logs, + decimal h = 0.0001m) + { + logs = new List(); + if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) + { + throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); + } + + int n = eqs.Count; + List vars = initPoints.Keys.ToList(); + Dictionary currentPoints = new Dictionary(initPoints); + + List compiledEqs = new List(n); + for (int i = 0; i < n; i++) + { + compiledEqs.Add(CompileFunction(eqs[i])); + } + + decimal tolerance = 0.0000000001m; // 1e-10m + + for (int iter = 1; iter <= iterationCount; iter++) + { + decimal[] F = new decimal[n]; + decimal maxAbsF = 0m; + + for (int i = 0; i < n; i++) + { + F[i] = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + decimal absF = DecimalMath.Abs(F[i]); + if (absF > maxAbsF) maxAbsF = absF; + } + + if (maxAbsF <= tolerance) + { + logs.Add($"[Adım {iter - 1}] Yakınsama sağlandı! Maksimum hata |F| = {maxAbsF:E4}"); + break; + } + + // Compute Jacobian Matrix J[i][j] = df_i / dx_j via central finite difference + decimal[][] J = new decimal[n][]; + for (int i = 0; i < n; i++) + { + J[i] = new decimal[n]; + for (int j = 0; j < n; j++) { - if ((le[j] == '+' || le[j] == '-') && j != 0) break; - if (le[j] == '*') + string vName = vars[j]; + decimal origVal = currentPoints[vName]; + + currentPoints[vName] = origVal + h; + decimal fPlus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + + currentPoints[vName] = origVal - h; + decimal fMinus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + + currentPoints[vName] = origVal; + J[i][j] = (fPlus - fMinus) / (2m * h); + } + } + + decimal[] negF = new decimal[n]; + for (int i = 0; i < n; i++) negF[i] = -F[i]; + + decimal[] delta; + try + { + delta = Matrix.SolveEquation(J, negF); + } + catch + { + // Perturb slightly if Jacobian is singular at initial guess (e.g. (0,0) for x^2+y^2) + for (int j = 0; j < n; j++) + { + currentPoints[vars[j]] += 0.01m * (j + 1); + } + logs.Add($"[Adım {iter}] Jakobiyen matrisi tekil (singular) noktaya denk geldi, nokta hafifçe kaydırılıyor..."); + continue; + } + + decimal maxStep = 0m; + for (int j = 0; j < n; j++) + { + currentPoints[vars[j]] += delta[j]; + decimal absD = DecimalMath.Abs(delta[j]); + if (absD > maxStep) maxStep = absD; + } + + string ptSummary = string.Join(", ", vars.Select(v => $"{v} = {currentPoints[v].ToString("0.########", CultureInfo.InvariantCulture)}")); + logs.Add($"[Adım {iter}] {ptSummary} (|Δ| = {maxStep:E3})"); + + if (maxStep <= tolerance) + { + logs.Add($"[Adım {iter}] Çözüm başarıyla yakınsadı."); + break; + } + } + + return currentPoints; + } + + public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.005m) + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + decimal constant = Method_EvaluateFunction(eq, variable, point); + if (DecimalMath.Abs(constant) <= 0.000001m) constant = 0; + + List terms = new List(); + if (constant != 0) + { + terms.Add(FormatCoeff(constant)); + } + + for (int i = 1; i <= degree; i++) + { + decimal step = i >= 4 ? 0.01m : h; + decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, step); + decimal fact = Factorial(i); + decimal coeff = der / fact; + + if (DecimalMath.Abs(coeff) <= 0.000001m) continue; + + string varPart = FormatVarPower(variable, point, i); + string coeffStr = FormatTermWithCoeff(coeff, varPart, terms.Count == 0); + terms.Add(coeffStr); + } + + if (terms.Count == 0) return "0"; + return string.Join(" ", terms); + } + + public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.005m) + { + if (points == null || points.Count == 0) return "0"; + + Function compiled = CompileFunction(eq); + decimal constant = EvaluateCompiledMultiVar(compiled, points); + if (DecimalMath.Abs(constant) <= 0.00001m) constant = 0; + + List terms = new List(); + if (constant != 0) + { + terms.Add(FormatCoeff(constant)); + } + + List varNames = points.Keys.ToList(); + int kVars = varNames.Count; + + for (int totalDeg = 1; totalDeg <= degree; totalDeg++) + { + List multiIndices = GenerateMultiIndices(kVars, totalDeg); + foreach (int[] alpha in multiIndices) + { + decimal mixedDer = ComputeMixedPartialDerivative(compiled, varNames, alpha, points, h); + decimal denom = 1m; + for (int j = 0; j < kVars; j++) + { + denom *= Factorial(alpha[j]); + } + + decimal coeff = mixedDer / denom; + if (DecimalMath.Abs(coeff) <= 0.00001m) continue; + + List factors = new List(); + for (int j = 0; j < kVars; j++) + { + if (alpha[j] > 0) { - charCount = 0; - break; + string vName = varNames[j]; + factors.Add(FormatVarPower(vName, points[vName], alpha[j])); } - charCount++; - if (j == le.Length - 1 && charCount != 0) charCount = 0; } - //Debug.Log(le + " | " + charCount); - - decimal leftV = charCount != 0 ? decimal.Parse(le.Substring(0, charCount)) * -1 : 0; - - - string sum = ""; - foreach (KeyValuePair p in dynamicPoints) - { - sum += p.Key + ": " + p.Value.ToString("0." + new string('#', 339)) + ", "; - } - - //Debug.Log(le + " | " + charCount + " | " + sum + " | " + leftV); - - le = le.Remove(0, le[charCount] == '-' ? charCount : charCount + 1); - - - foreach (KeyValuePair p in dynamicPoints) - { - le = le.Replace("(" + p.Key + (p.Value < 0 ? "+" + DecimalMath.Abs(p.Value).ToString("0." + new string('#', 339)) : "-" + p.Value.ToString("0." + new string('#', 339))) + ")", p.Key); - } - //Debug.Log(le); - - - linearizedEqs.Add(le); - leftVector.Add(leftV); + string varPart = string.Join(" * ", factors); + terms.Add(FormatTermWithCoeff(coeff, varPart, terms.Count == 0)); } - - foreach (KeyValuePair p in dynamicPoints) - { - variablesStr.Add(p.Key); - } - - decimal[][] jacobianMatrix = Matrix.ConvertLinearEquationsToMatrix(linearizedEqs, variablesStr); - decimal[] leftHandVector = leftVector.ToArray(); - - decimal[] newPoints = Matrix.SolveEquation(jacobianMatrix, leftHandVector); - - - List newPointsList = new List(); - - for (int i = 0; i < newPoints.Length; i++) - { - newPointsList.Add(newPoints[i]); - } - - Dictionary tempDynamicPoints = new Dictionary(); - - foreach (KeyValuePair p in dynamicPoints) - { - tempDynamicPoints.Add(p.Key, p.Value); - } - - foreach (KeyValuePair p in dynamicPoints) - { - tempDynamicPoints[p.Key] = newPointsList[0] + p.Value; - newPointsList.RemoveAt(0); - } - dynamicPoints = tempDynamicPoints; } - return dynamicPoints; + if (terms.Count == 0) return "0"; + return string.Join(" ", terms); } - - public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.001m) + private static List GenerateMultiIndices(int numVars, int totalSum) { - decimal constant = Method_EvaluateFunction(eq, variable, point); - constant = DecimalMath.Abs(constant) <= 0.001m ? 0 : constant; - string newEq = constant != 0 ? constant.ToString("0." + new string('#', 339)) : ""; - for (int i = 1; i < degree + 1; i++) - { - //decimal der = Method_Derivative(eq, i, variable, point); - decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, h); - decimal fact = Factorial(i); - decimal coeff = (der / fact); - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; - - string addingSTR = ""; - if (point < 0) - { - addingSTR = "+" + DecimalMath.Abs(point).ToString("0." + new string('#', 339)); - } - else if (point > 0) - { - addingSTR = "-" + point.ToString("0." + new string('#', 339)); - } - - varSTR += coeff + "*(" + variable + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339)) + ""); - newEq += varSTR; - } - return newEq; - } - /*public static string Method_TaylorSeries2(string eq, int degree, string variable, decimal point) - { - decimal constant = Method_EvaluateFunction(eq, variable, point); - constant = DecimalMath.Abs(constant) <= 0.0001m ? 0 : constant; - - string newEq = constant.ToString("0." + new string('#', 339)); - for (int i = 1; i < degree + 1; i++) - { - decimal der = Method_Derivative(eq, i, variable, point); - //Debug.Log("derivative at " + i + ": " + der.ToString()); - if (DecimalMath.Abs(der) <= 0.0001m) - { - der = 0; - Debug.Log(der + ": " + 0); - } - decimal fact = Factorial(i); - decimal coeff = (der / fact); - - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; - - string addingSTR = ""; - if (point < 0) - { - addingSTR = "+" + DecimalMath.Abs(point).ToString("0." + new string('#', 339)); - } - else if (point > 0) - { - addingSTR = "-" + point.ToString("0." + new string('#', 339)); - } - - varSTR += coeff + "*(" + variable + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339))); - newEq += varSTR; - } - return newEq; - }*/ - public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.001m) - { - decimal constant = MethodMultiVar_EvaluateFunction(eq, points); - constant = DecimalMath.Abs(constant) <= 0.0001m ? 0 : constant; - string newEq = constant != 0 ? constant.ToString("0." + new string('#', 339)) : ""; - for (int i = 1; i < degree + 1; i++) - { - foreach (KeyValuePair pt in points) - { - decimal partDer = Method_NumericalPartialDifferentiation(eq, i, pt.Key, points, 4, h); - //decimal partDer = Method_PartialDerivative(eq, i, pt.Key, points, h); - decimal fact = Factorial(i); - decimal coeff = partDer / fact; - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; - - string addingSTR = ""; - if (pt.Value < 0) - { - addingSTR = "+" + DecimalMath.Abs(pt.Value).ToString("0." + new string('#', 339)); - } - else if (pt.Value > 0) - { - addingSTR = "-" + pt.Value.ToString("0." + new string('#', 339)); - } - varSTR += coeff + "*(" + pt.Key + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339))); - newEq += varSTR; - } - } - //Debug.Log(newEq + " + " + constant + " | " + eq); - if (constant == 0) newEq.Substring(0, 1); - return newEq; + List results = new List(); + int[] current = new int[numVars]; + GenerateMultiIndicesRecursive(numVars, totalSum, 0, current, results); + return results; } - - public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.001m) + private static void GenerateMultiIndicesRecursive(int numVars, int remaining, int idx, int[] current, List results) { - decimal Lipschitz = Method_EvaluateFunction(eq, variable, initialValue) * Method_NumericalDifferentiation(eq, 2, variable, initialValue, 6, h) / - Method_NumericalDifferentiation(eq, 1, variable, initialValue, 6, h) / Method_NumericalDifferentiation(eq, 1, variable, initialValue, 6, h); + if (idx == numVars - 1) + { + current[idx] = remaining; + results.Add((int[])current.Clone()); + return; + } + for (int v = remaining; v >= 0; v--) + { + current[idx] = v; + GenerateMultiIndicesRecursive(numVars, remaining - v, idx + 1, current, results); + } + } - if (Lipschitz < 1) { } + private static decimal ComputeMixedPartialDerivative( + Function f, + List varNames, + int[] orders, + Dictionary basePoints, + decimal h) + { + Dictionary workPoints = new Dictionary(basePoints); + return ComputeMixedRecursive(f, varNames, orders, 0, workPoints, h); + } + + private static decimal ComputeMixedRecursive( + Function f, + List varNames, + int[] orders, + int varIndex, + Dictionary workPoints, + decimal h) + { + while (varIndex < orders.Length && orders[varIndex] == 0) + { + varIndex++; + } + + if (varIndex >= orders.Length) + { + return EvaluateCompiledMultiVar(f, workPoints); + } + + string vName = varNames[varIndex]; + int m = orders[varIndex]; + decimal origVal = workPoints[vName]; + + // Central finite difference weights for order m + decimal sum = 0m; + for (int i = 0; i <= m; i++) + { + decimal shift = (m - 2m * i) * (h * 0.5m); + workPoints[vName] = origVal + shift; + decimal sign = (i % 2 == 0) ? 1m : -1m; + decimal comb = Combination(m, i); + decimal subVal = ComputeMixedRecursive(f, varNames, orders, varIndex + 1, workPoints, h); + sum += sign * comb * subVal; + } + + workPoints[vName] = origVal; + return sum / DecimalMath.Pow(h, m); + } + + private static string FormatCoeff(decimal c) + { + decimal rounded = Math.Round(c, 6); + foreach (int denom in new[] { 1, 2, 3, 4, 6, 8, 12 }) + { + decimal candidate = Math.Round(c * denom) / (decimal)denom; + if (DecimalMath.Abs(c - candidate) < 0.00005m) + { + rounded = candidate; + break; + } + } + return rounded.ToString("0.######", CultureInfo.InvariantCulture); + } + + private static string FormatVarPower(string variable, decimal center, int power) + { + string core; + if (center == 0m) + { + core = variable; + } + else if (center > 0m) + { + core = $"({variable} - {FormatCoeff(center)})"; + } else { - Debug.LogError("Wrong initial value!"); - return 0; + core = $"({variable} + {FormatCoeff(DecimalMath.Abs(center))})"; } - decimal init = initialValue; + if (power == 1) return core; + return $"{core}^{power}"; + } + + private static string FormatTermWithCoeff(decimal coeff, string varPart, bool isFirst) + { + decimal absC = DecimalMath.Abs(coeff); + string sign = coeff < 0 ? (isFirst ? "-" : "- ") : (isFirst ? "" : "+ "); + string cStr = FormatCoeff(absC); + + if (cStr == "1") + { + return $"{sign}{varPart}"; + } + return $"{sign}{cStr}*{varPart}"; + } + + public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.0001m) + { + Function f = CompileFunction(eq); + decimal curr = initialValue; for (int i = 0; i < iterationCount; i++) { - //decimal next = init - Method_EvaluateFunction(eq, variable, init) / Method_Derivative(eq, 1, variable, init, h); - decimal next = init - Method_EvaluateFunction(eq, variable, init) / Method_NumericalDifferentiation(eq, 1, variable, init, 6, h); - init = next; + decimal fx = EvaluateCompiled(f, variable, curr); + if (DecimalMath.Abs(fx) <= 1e-12m) break; + + decimal dfx = (EvaluateCompiled(f, variable, curr + h) - EvaluateCompiled(f, variable, curr - h)) / (2m * h); + if (DecimalMath.Abs(dfx) <= 1e-15m) break; + + curr = curr - fx / dfx; } - return init; + return curr; } + public static decimal Method_BisectionMethod(string eq, string variable, decimal lowerValue, decimal higherValue, int iterationCount) { - if (lowerValue >= higherValue) - return 0; + if (lowerValue >= higherValue) return lowerValue; - decimal mp = (lowerValue + higherValue) / 2; + Function f = CompileFunction(eq); + decimal fa = EvaluateCompiled(f, variable, lowerValue); + if (DecimalMath.Abs(fa) <= 1e-12m) return lowerValue; + decimal fb = EvaluateCompiled(f, variable, higherValue); + if (DecimalMath.Abs(fb) <= 1e-12m) return higherValue; + + decimal mp = (lowerValue + higherValue) / 2m; for (int i = 0; i < iterationCount; i++) { - mp = (lowerValue + higherValue) / 2; + mp = (lowerValue + higherValue) / 2m; + decimal evMiddle = EvaluateCompiled(f, variable, mp); - decimal evLower = Method_EvaluateFunction(eq, variable, lowerValue); - decimal evHigher = Method_EvaluateFunction(eq, variable, higherValue); - decimal evMiddle = Method_EvaluateFunction(eq, variable, mp); + if (DecimalMath.Abs(evMiddle) <= 1e-12m) break; - if (evLower * evMiddle < 0) + if (fa * evMiddle <= 0) { higherValue = mp; + fb = evMiddle; } else { lowerValue = mp; + fa = evMiddle; } } return mp; } - public static decimal Method_Derivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - decimal sum = 0; - for (int i = 0; i <= degree; i++) - { - sum += DecimalMath.Pow(-1, i) * Combination(degree, i) * Method_EvaluateFunction(eq, variable, point + (degree - i) * h); - //Debug.Log(sum); - } - - decimal res = sum / DecimalMath.Pow(h, degree); - - //Debug.Log(sum.ToString("0." + new string('#', 339)) + " || " + Math.Pow((double)h, degree).ToString() + " | " + Math.Pow((double)h, degree).ToString("0." + new string('#', 339))); - //Debug.Log(res + " || " + sum.ToString("0." + new string('#', 339)) + " || " + DecimalMath.Pow(h, degree).ToString() + " | " + DecimalMath.Pow(h, degree).ToString("0." + new string('#', 339))); - - return res; + return Method_NumericalDifferentiation(eq, degree, variable, point, 4, h); } + public static decimal Method_PartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) { - decimal sum = 0; - Dictionary testPS = new Dictionary(); - foreach (KeyValuePair item in points) - { - testPS.Add(item.Key, item.Value); - } - decimal firstToVar = testPS[toVar]; - for (int i = 0; i <= degree; i++) - { - testPS[toVar] = firstToVar + (degree - i) * h; - sum += DecimalMath.Pow(-1, i) * Combination(degree, i) * MethodMultiVar_EvaluateFunction(eq, testPS); - } - decimal res = sum / DecimalMath.Pow(h, degree); - return res; + return Method_NumericalPartialDifferentiation(eq, degree, toVar, points, 4, h); } - public static decimal Method_NumericalDifferentiation(string eq, int degree, string variable, decimal point, int accuracy = 2, decimal h = 0.001m) { - decimal result = 0; - int m = degree, n = accuracy; - int p = (2 * Mathf.FloorToInt((m + 1) / 2) - 2 + n) / 2; + if (m >= 11) { n = 2; h = 0.08m; } + else if (m == 10) { n = 2; h = 0.04m; } + else if (m == 9) { n = 4; h = 0.015m; } + else if (m >= 7 && h < 0.012m) h = 0.012m; + + Function f = CompileFunction(eq); + int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; decimal[][] _matrix = new decimal[2 * p + 1][]; - decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], + decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], functionPointsY = new decimal[2 * p + 1]; - for (int i = 0; i < _matrix.Length; i++) { _matrix[i] = new decimal[2 * p + 1]; for (int j = 0; j < _matrix[i].Length; j++) { - _matrix[i][j] = (decimal)Mathf.Pow(-p + j, i); + _matrix[i][j] = DecimalMath.PowerN(-p + j, i); } - - if (i != m) - { - _rhsVector[i] = 0; - } - else if (i == m) - { - _rhsVector[i] = Factorial(m); - } - - + _rhsVector[i] = (i == m) ? Factorial(m) : 0m; functionPointsX[i] = point - (p - i) * h; - functionPointsY[i] = Method_EvaluateFunction(eq, variable, functionPointsX[i]); + functionPointsY[i] = EvaluateCompiled(f, variable, functionPointsX[i]); } GeneralMatrix _A = new GeneralMatrix(_matrix); @@ -447,9 +487,7 @@ public class NumericalMethods _b.Array[i][0] = _rhsVector[i]; } - //decimal[] coeffs = Matrix.SolveEquation(_matrix, _rhsVector); GeneralMatrix coeffs = _A.Solve(_b); - decimal sum = 0; for (int i = 0; i < coeffs.Array.Length; i++) @@ -457,87 +495,60 @@ public class NumericalMethods sum += coeffs.Array[i][0] * functionPointsY[i]; } - result = sum / DecimalMath.Pow(h, degree); - - return result; + return sum / DecimalMath.Pow(h, degree); } + public static decimal Method_NumericalPartialDifferentiation(string eq, int degree, string toVar, Dictionary points, int accuracy = 2, decimal h = 0.001m) { - decimal result = 0; - + Function f = CompileFunction(eq); int m = degree, n = accuracy; - int p = (2 * Mathf.FloorToInt((m + 1) / 2) - 2 + n) / 2; + int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; decimal[][] _matrix = new decimal[2 * p + 1][]; Dictionary functionPointsDomain = new Dictionary(); decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsRange = new decimal[2 * p + 1]; - for (int i = 0; i < _matrix.Length; i++) { _matrix[i] = new decimal[2 * p + 1]; for (int j = 0; j < _matrix[i].Length; j++) { - _matrix[i][j] = (decimal)Mathf.Pow(-p + j, i); + _matrix[i][j] = DecimalMath.PowerN(-p + j, i); } - if (i != m) - { - _rhsVector[i] = 0; - } - else if (i == m) - { - _rhsVector[i] = Factorial(m); - } + _rhsVector[i] = (i == m) ? Factorial(m) : 0m; } foreach (KeyValuePair item in points) { decimal[] ps = new decimal[2 * p + 1]; - if (item.Key == toVar) { - for (int i = 0; i < ps.Length; i++) - { - ps[i] = points[item.Key] - (p - i) * h; - } + for (int i = 0; i < ps.Length; i++) ps[i] = points[item.Key] - (p - i) * h; } else { - for (int i = 0; i < ps.Length; i++) - { - ps[i] = points[item.Key]; - } + for (int i = 0; i < ps.Length; i++) ps[i] = points[item.Key]; } - functionPointsDomain.Add(item.Key, ps); } - for (int i = 0; i < 2 * p + 1; i++) { Dictionary pair = new Dictionary(); - foreach (KeyValuePair item in functionPointsDomain) { pair.Add(item.Key, item.Value[i]); } - - functionPointsRange[i] = MethodMultiVar_EvaluateFunction(eq, pair); + functionPointsRange[i] = EvaluateCompiledMultiVar(f, pair); } - GeneralMatrix _A = new GeneralMatrix(_matrix); GeneralMatrix _b = new GeneralMatrix(_rhsVector.Length, 1); - for (int i = 0; i < _rhsVector.Length; i++) - { - _b.Array[i][0] = _rhsVector[i]; - } + for (int i = 0; i < _rhsVector.Length; i++) _b.Array[i][0] = _rhsVector[i]; - //decimal[] coeffs = Matrix.SolveEquation(_matrix, _rhsVector); GeneralMatrix coeffs = _A.Solve(_b); - decimal sum = 0; for (int i = 0; i < coeffs.Array.Length; i++) @@ -545,65 +556,49 @@ public class NumericalMethods sum += coeffs.Array[i][0] * functionPointsRange[i]; } - result = sum / DecimalMath.Pow(h, degree); - - return result; + return sum / DecimalMath.Pow(h, degree); } - #region testPow - /*public static decimal Pow(decimal x, uint y) + public static decimal Factorial(int num) { - decimal A = 1m; - BitArray e = new BitArray(BitConverter.GetBytes(y)); - int t = e.Count; - - for (int i = t - 1; i >= 0; --i) - { - A *= A; - if (e[i] == true) - { - A *= x; - } - } - return A; - }*/ - #endregion - - public static int Factorial(int num) - { - if (num >= 2) - { - return num * Factorial(num -1); - } - else - { - return 1; - } + if (num < 0) return 0m; + decimal res = 1m; + for (int i = 2; i <= num; i++) res *= i; + return res; } - public static int Combination(int n, int k) - { - int top = Factorial(n); - int bot1 = Factorial(n - k); - int bot2 = Factorial(k); - return top / bot1 / bot2; + public static decimal Combination(int n, int k) + { + if (k < 0 || k > n || n < 0) return 0m; + if (k == 0 || k == n) return 1m; + if (k > n - k) k = n - k; + decimal res = 1m; + for (int i = 1; i <= k; i++) + { + res = (res * (n - k + i)) / i; + } + return res; } - public static int Permutation(int n, int k) - { - int top = Factorial(n); - int bot = Factorial(n - k); - return top / bot; + public static decimal Permutation(int n, int k) + { + if (k < 0 || k > n || n < 0) return 0m; + if (k == 0) return 1m; + decimal res = 1m; + for (int i = 0; i < k; i++) + { + res *= (n - i); + } + return res; } public static string GenerateCombinations(string chars, string prefix, int length) { StringBuilder sb = new StringBuilder(); - GenerateCombinationsRecursive(prefix, chars, length, sb); - return sb.ToString(); } + static void GenerateCombinationsRecursive(string prefix, string chars, int length, StringBuilder sb) { if (length == 0) @@ -617,5 +612,503 @@ public class NumericalMethods GenerateCombinationsRecursive(prefix + c, chars, length - 1, sb); } } -} + /// + /// Gauss-Seidel Iterative Linear System Solver with Diagonal Dominance Verification & Row Reordering. + /// Ported and enhanced from NumericalMethods / NumericalMethods2. + /// + public static Dictionary Method_GaussSeidel( + List eqs, + Dictionary initPoints, + int iterationCount, + out List logs) + { + logs = new List(); + if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) + { + throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); + } + + int n = eqs.Count; + List vars = initPoints.Keys.ToList(); + + // Extract linear matrix A and right-hand vector b such that A * x = b + // Note: ConvertLinearEquationsToMatrix evaluates f(x) = LHS - RHS = A*x - b + decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); + decimal[] b = new decimal[n]; + Dictionary zeroPts = new Dictionary(); + foreach (string v in vars) zeroPts[v] = 0m; + + for (int i = 0; i < n; i++) + { + string normEq = NormalizeEquation(eqs[i]); + // f(0) = -b => b = -f(0) + b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); + } + + // Check / reorder rows for diagonal dominance: |a_ii| > sum_{j != i} |a_ij| + int[] dominantColForRow = new int[n]; + bool strictDominance = true; + for (int i = 0; i < n; i++) + { + int domCol = -1; + for (int j = 0; j < n; j++) + { + decimal sumOthers = 0m; + for (int k = 0; k < n; k++) + { + if (k != j) sumOthers += DecimalMath.Abs(A[i][k]); + } + if (DecimalMath.Abs(A[i][j]) >= sumOthers && DecimalMath.Abs(A[i][j]) > 0m) + { + domCol = j; + break; + } + } + dominantColForRow[i] = domCol; + if (domCol == -1) strictDominance = false; + } + + // Attempt to permute rows if each row has a distinct dominant column + if (strictDominance && dominantColForRow.Distinct().Count() == n) + { + decimal[][] newA = new decimal[n][]; + decimal[] newB = new decimal[n]; + for (int i = 0; i < n; i++) + { + int targetRow = dominantColForRow[i]; + newA[targetRow] = A[i]; + newB[targetRow] = b[i]; + } + A = newA; + b = newB; + logs.Add("✓ Köşegen baskınlığı (Diagonal Dominance) doğrulandı (|a_ii| ≥ Σ|a_ij|)."); + } + else + { + logs.Add("⚠️ Uyarı: Matris tam köşegen baskın değil; Gauss-Seidel yakınsamayabilir."); + } + + decimal[] x = new decimal[n]; + for (int i = 0; i < n; i++) x[i] = initPoints[vars[i]]; + + decimal tol = 1e-10m; + for (int iter = 1; iter <= iterationCount; iter++) + { + decimal maxDiff = 0m; + for (int i = 0; i < n; i++) + { + if (DecimalMath.Abs(A[i][i]) <= 1e-15m) + { + throw new ArithmeticException($"Köşegen elemanı A[{i + 1},{i + 1}] = 0 olduğu için Gauss-Seidel uygulanamaz."); + } + + decimal sigma = 0m; + for (int j = 0; j < n; j++) + { + if (j != i) sigma += A[i][j] * x[j]; + } + + decimal nextXi = (b[i] - sigma) / A[i][i]; + decimal diff = DecimalMath.Abs(nextXi - x[i]); + if (diff > maxDiff) maxDiff = diff; + x[i] = nextXi; + } + + string stepStr = string.Join(", ", Enumerable.Range(0, n).Select(idx => $"{vars[idx]} = {x[idx].ToString("0.########", CultureInfo.InvariantCulture)}")); + logs.Add($"[Adım {iter,2}] {stepStr} (|Δ| = {maxDiff:E3})"); + + if (maxDiff <= tol) + { + logs.Add($"✓ Gauss-Seidel {iter}. adımda başarıyla yakınsadı."); + break; + } + } + + Dictionary result = new Dictionary(); + for (int i = 0; i < n; i++) result[vars[i]] = x[i]; + return result; + } + + public static Dictionary Method_LinearMatrixSolve( + List eqs, + List vars, + string methodType, + out List logs) + { + logs = new List(); + int n = eqs.Count; + decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); + decimal[] b = new decimal[n]; + + Dictionary zeroPts = new Dictionary(); + foreach (string v in vars) zeroPts[v] = 0m; + bool isNonLinear = false; + for (int i = 0; i < n; i++) + { + string normEq = NormalizeEquation(eqs[i]); + b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); + + if (vars.Count > 0) + { + zeroPts[vars[0]] = 2m; + decimal f2 = MethodMultiVar_EvaluateFunction(normEq, zeroPts); + zeroPts[vars[0]] = 0m; + if (DecimalMath.Abs(f2 - (2m * A[i][0] - b[i])) > 1e-4m) + { + isNonLinear = true; + } + } + } + + if (isNonLinear) + { + logs.Add("UYARI: Denklemler doğrusal değil. Çözüm doğrusal yaklaşım olarak sunulmuştur."); + } + + logs.Add("--- Katsayılar Matrisi (A) ve Sağ Taraf Vektörü (b) ---"); + for (int i = 0; i < n; i++) + { + string rowStr = string.Join(" ", A[i].Select(v => $"{v,8:0.####}")); + logs.Add($" [ {rowStr} ] | [ {b[i],8:0.####} ]"); + } + logs.Add(""); + + GeneralMatrix gA = new GeneralMatrix(A); + GeneralMatrix gB = new GeneralMatrix(n, 1); + for (int i = 0; i < n; i++) gB.Array[i][0] = b[i]; + + GeneralMatrix gX; + if (methodType == "INVERSE") + { + logs.Add("Yöntem: Ters Matris (X = A⁻¹ · b)"); + GeneralMatrix invA = gA.Inverse(); + gX = invA.Multiply(gB); + } + else if (methodType == "QR") + { + logs.Add("Yöntem: QR Ayrışımı (Q·R·X = b)"); + gX = gA.QRD().Solve(gB); + } + else + { + logs.Add("Yöntem: LU Ayrışımı (L·U·X = P·b)"); + gX = gA.LUD().Solve(gB); + } + + Dictionary res = new Dictionary(); + for (int i = 0; i < n; i++) + { + res[vars[i]] = gX.Array[i][0]; + logs.Add($" {vars[i]} = {Math.Round(gX.Array[i][0], 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + } + return res; + } + + public static decimal Method_BackwardDifferenceDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) + { + Function f = CompileFunction(eq); + decimal f0 = EvaluateCompiled(f, variable, point); + decimal f1 = EvaluateCompiled(f, variable, point - h); + decimal f2 = EvaluateCompiled(f, variable, point - 2m * h); + + if (degree == 1) + { + return (3m * f0 + f2 - 4m * f1) / (2m * h); + } + else if (degree == 2) + { + return (f0 + f2 - 2m * f1) / (h * h); + } + else if (degree == 3) + { + decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); + decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); + return (3m * f4 - 14m * f3 + 24m * f2 - 18m * f1 + 5m * f0) / (2m * h * h * h); + } + else if (degree == 4) + { + decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); + decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); + decimal f5 = EvaluateCompiled(f, variable, point - 5m * h); + return (-2m * f5 + 11m * f4 - 24m * f3 + 26m * f2 - 14m * f1 + 3m * f0) / (h * h * h * h); + } + else + { + return Method_ForwardBinomialDerivative(eq, degree, variable, point, h); + } + } + + public static decimal Method_ForwardBinomialDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) + { + Function f = CompileFunction(eq); + decimal sum = 0m; + for (int i = 0; i <= degree; i++) + { + decimal sign = (i % 2 == 0) ? 1m : -1m; + sum += sign * Combination(degree, i) * EvaluateCompiled(f, variable, point + (degree - i) * h); + } + return sum / DecimalMath.Pow(h, degree); + } + + public static decimal Method_ForwardBinomialPartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) + { + Function f = CompileFunction(eq); + decimal sum = 0m; + Dictionary testPS = new Dictionary(points); + decimal firstToVar = testPS[toVar]; + for (int i = 0; i <= degree; i++) + { + testPS[toVar] = firstToVar + (degree - i) * h; + decimal sign = (i % 2 == 0) ? 1m : -1m; + sum += sign * Combination(degree, i) * EvaluateCompiledMultiVar(f, testPS); + } + return sum / DecimalMath.Pow(h, degree); + } + + // --- Root Finding Methods with Full Iteration Logs & Variable Support --- + + public static List Method_NewtonRaphson(string _eq, decimal _initialPoint, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + decimal x = _initialPoint; + decimal h = 0.0001m; + decimal tol = 1e-12m; + + logs.Add($"--- Newton-Raphson Yöntemi (Başlangıç: {variable}₀ = {x.ToString(CultureInfo.InvariantCulture)}) ---"); + + for (int i = 1; i <= _iterationCount; i++) + { + decimal fx = EvaluateCompiled(f, variable, x); + decimal dfx = (EvaluateCompiled(f, variable, x + h) - EvaluateCompiled(f, variable, x - h)) / (2m * h); + + if (DecimalMath.Abs(dfx) <= 1e-15m) + { + logs.Add($"[Adım {i}] Türev sıfıra çok yakın (f'({variable}) ≈ 0). İşlem durduruldu."); + break; + } + + decimal nextX = x - fx / dfx; + decimal err = DecimalMath.Abs(nextX - x); + x = nextX; + + logs.Add($"[Adım {i,2}] {variable} = {x.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fx.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (err <= tol || DecimalMath.Abs(fx) <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, x); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {x.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_Bisection(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal a = _min; + decimal b = _max; + if (a >= b) + { + return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; + } + + decimal fa = EvaluateCompiled(f, variable, a); + decimal fb = EvaluateCompiled(f, variable, b); + + if (DecimalMath.Abs(fa) <= 1e-12m) + { + logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + if (DecimalMath.Abs(fb) <= 1e-12m) + { + logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + + if (fa * fb > 0) + { + return new List + { + $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", + $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", + "Bisection (İkiye Bölme) yöntemi için f(Min) * f(Max) <= 0 olmalıdır." + }; + } + + logs.Add($"--- Bisection (İkiye Bölme) Yöntemi [{a}, {b}] ---"); + decimal mid = (a + b) / 2m; + decimal tol = 1e-11m; + + for (int i = 1; i <= _iterationCount; i++) + { + mid = (a + b) / 2m; + decimal fMid = EvaluateCompiled(f, variable, mid); + decimal width = (b - a) / 2m; + + logs.Add($"[Adım {i,2}] {variable} = {mid.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fMid.ToString("E3", CultureInfo.InvariantCulture),-11} | Aralık: [{a:0.####}, {b:0.####}]"); + + if (DecimalMath.Abs(fMid) <= tol || width <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + + if (fa * fMid <= 0) + { + b = mid; + fb = fMid; + } + else + { + a = mid; + fa = fMid; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, mid); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {mid.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_Secant(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal x0 = _min; + decimal x1 = _max; + decimal x2 = x1; + decimal tol = 1e-11m; + + logs.Add($"--- Secant (Kiriş) Yöntemi ({variable}₀ = {x0}, {variable}₁ = {x1}) ---"); + + for (int i = 1; i <= _iterationCount; i++) + { + decimal f0 = EvaluateCompiled(f, variable, x0); + decimal f1 = EvaluateCompiled(f, variable, x1); + + if (DecimalMath.Abs(f1 - f0) <= 1e-15m) + { + logs.Add($"[Adım {i}] f({variable}₁) - f({variable}₀) ≈ 0 oldu. İşlem durduruldu."); + break; + } + + x2 = x1 - f1 * (x1 - x0) / (f1 - f0); + decimal err = DecimalMath.Abs(x2 - x1); + x0 = x1; + x1 = x2; + + decimal f2 = EvaluateCompiled(f, variable, x2); + logs.Add($"[Adım {i,2}] {variable} = {x2.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {f2.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (err <= tol || DecimalMath.Abs(f2) <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, x2); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {x2.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_RegulaFalsi(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal a = _min; + decimal b = _max; + if (a >= b) + { + return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; + } + + decimal fa = EvaluateCompiled(f, variable, a); + decimal fb = EvaluateCompiled(f, variable, b); + + if (DecimalMath.Abs(fa) <= 1e-12m) + { + logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + if (DecimalMath.Abs(fb) <= 1e-12m) + { + logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + + if (fa * fb > 0) + { + return new List + { + $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", + $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", + "Regula Falsi yöntemi için f(Min) * f(Max) <= 0 olmalıdır." + }; + } + + logs.Add($"--- Regula Falsi (Yer Değiştirme) Yöntemi [{a}, {b}] ---"); + decimal c = a; + decimal tol = 1e-11m; + int side = 0; + + for (int i = 1; i <= _iterationCount; i++) + { + if (DecimalMath.Abs(fb - fa) <= 1e-15m) break; + + decimal prevC = c; + c = (a * fb - b * fa) / (fb - fa); + decimal fc = EvaluateCompiled(f, variable, c); + decimal err = DecimalMath.Abs(c - prevC); + + logs.Add($"[Adım {i,2}] {variable} = {c.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fc.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (DecimalMath.Abs(fc) <= tol || (i > 1 && err <= tol)) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + + if (fa * fc <= 0) + { + b = c; + fb = fc; + if (side == -1) fa *= 0.5m; + side = -1; + } + else + { + a = c; + fa = fc; + if (side == 1) fb *= 0.5m; + side = 1; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, c); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {c.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } +} diff --git a/MathApp/MathApp.sln b/MathApp/MathApp.sln index b968609..56a8310 100644 --- a/MathApp/MathApp.sln +++ b/MathApp/MathApp.sln @@ -1,22 +1,22 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathApp", "MathApp\MathApp.csproj", "{AABBCCDD-1234-5678-90AB-CDEF12345678}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MathApp", "MathApp\MathApp.csproj", "{F69EC879-1E4E-41CF-A04B-2E5DD14E43D2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {AABBCCDD-1234-5678-90AB-CDEF12345678}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AABBCCDD-1234-5678-90AB-CDEF12345678}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AABBCCDD-1234-5678-90AB-CDEF12345678}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AABBCCDD-1234-5678-90AB-CDEF12345678}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F69EC879-1E4E-41CF-A04B-2E5DD14E43D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F69EC879-1E4E-41CF-A04B-2E5DD14E43D2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F69EC879-1E4E-41CF-A04B-2E5DD14E43D2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F69EC879-1E4E-41CF-A04B-2E5DD14E43D2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection EndGlobal diff --git a/MathApp/MathApp/Controls/CombinatoricsControl.Designer.cs b/MathApp/MathApp/Controls/CombinatoricsControl.Designer.cs new file mode 100644 index 0000000..cb137c7 --- /dev/null +++ b/MathApp/MathApp/Controls/CombinatoricsControl.Designer.cs @@ -0,0 +1,328 @@ +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class CombinatoricsControl + { + private System.ComponentModel.IContainer components = null; + private Panel pnlLeft; + private Label lblTitle; + private Label lblDesc; + + // Group 1: Combinatorics & Permutations + private GroupBox grpComb; + private Label lblN; + private NumericUpDown numN; + private Label lblR; + private NumericUpDown numR; + private Button btnCalcComb; + private Button btnPascal; + + // Group 2: String Combination Generator + private GroupBox grpStrings; + private Label lblAlphabet; + private TextBox txtAlphabet; + private Label lblPrefix; + private TextBox txtPrefix; + private Label lblLength; + private NumericUpDown numLength; + private Button btnGenStrings; + + // Group 3: Polar & Vector Coordinates + private GroupBox grpPolar; + private Label lblCoordX; + private TextBox txtCoordX; + private Label lblCoordY; + private TextBox txtCoordY; + private Button btnPolarConvert; + + // Group 4: Special Functions + private GroupBox grpSpecial; + private Label lblSpecialX; + private TextBox txtSpecialX; + private Label lblBase; + private TextBox txtBase; + private Button btnSpecialCalc; + + private RichTextBox txtOutput; + private Panel pnlRightHeader; + private Label lblOutputTitle; + private Button btnCopyOutput; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlLeft = new Panel(); + this.lblTitle = new Label(); + this.lblDesc = new Label(); + + this.grpComb = new GroupBox(); + this.lblN = new Label(); + this.numN = new NumericUpDown(); + this.lblR = new Label(); + this.numR = new NumericUpDown(); + this.btnCalcComb = new Button(); + this.btnPascal = new Button(); + + this.grpStrings = new GroupBox(); + this.lblAlphabet = new Label(); + this.txtAlphabet = new TextBox(); + this.lblPrefix = new Label(); + this.txtPrefix = new TextBox(); + this.lblLength = new Label(); + this.numLength = new NumericUpDown(); + this.btnGenStrings = new Button(); + + this.grpPolar = new GroupBox(); + this.lblCoordX = new Label(); + this.txtCoordX = new TextBox(); + this.lblCoordY = new Label(); + this.txtCoordY = new TextBox(); + this.btnPolarConvert = new Button(); + + this.grpSpecial = new GroupBox(); + this.lblSpecialX = new Label(); + this.txtSpecialX = new TextBox(); + this.lblBase = new Label(); + this.txtBase = new TextBox(); + this.btnSpecialCalc = new Button(); + + this.txtOutput = new RichTextBox(); + this.SuspendLayout(); + + this.BackColor = Color.FromArgb(24, 25, 32); + this.Dock = DockStyle.Fill; + this.Padding = new Padding(12); + + this.pnlLeft.Dock = DockStyle.Left; + this.pnlLeft.Width = 380; + this.pnlLeft.BackColor = Color.FromArgb(30, 32, 42); + this.pnlLeft.Padding = new Padding(12); + this.pnlLeft.AutoScroll = true; + + this.lblTitle.Text = "Kombinatorik & Özel Fonksiyonlar"; + this.lblTitle.Font = new Font("Segoe UI", 12.5F, FontStyle.Bold); + this.lblTitle.ForeColor = Color.White; + this.lblTitle.Location = new Point(12, 10); + this.lblTitle.AutoSize = true; + + this.lblDesc.Text = "Faktöriyel, Kombinasyon, Permütasyon, Dizi Üreteci, Polar/Atan2 ve Hiperbolik Fonksiyonlar."; + this.lblDesc.Font = new Font("Segoe UI", 8.5F); + this.lblDesc.ForeColor = Color.FromArgb(165, 175, 195); + this.lblDesc.Location = new Point(12, 34); + this.lblDesc.Size = new Size(350, 28); + + // Group 1: Combinatorics + StyleGroupBox(grpComb, "1. Kombinasyon, Permütasyon & Faktöriyel", new Point(12, 68), new Size(350, 115)); + StyleLabel(lblN, "n:", new Point(15, 26)); + ((System.ComponentModel.ISupportInitialize)(this.numN)).BeginInit(); + this.numN.Location = new Point(36, 23); + this.numN.Minimum = 0; + this.numN.Maximum = 60; + this.numN.Value = 10; + this.numN.Size = new Size(55, 23); + this.numN.BackColor = Color.FromArgb(40, 43, 56); + this.numN.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numN)).EndInit(); + + StyleLabel(lblR, "r (k):", new Point(105, 26)); + ((System.ComponentModel.ISupportInitialize)(this.numR)).BeginInit(); + this.numR.Location = new Point(145, 23); + this.numR.Minimum = 0; + this.numR.Maximum = 60; + this.numR.Value = 3; + this.numR.Size = new Size(55, 23); + this.numR.BackColor = Color.FromArgb(40, 43, 56); + this.numR.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numR)).EndInit(); + + StyleActionBtn(btnCalcComb, "n!, P(n,r), C(n,r) Hesapla", new Point(15, 54), new Size(320, 26)); + StyleActionBtn(btnPascal, "Pascal Üçgeni (Binom)", new Point(15, 83), new Size(320, 24)); + this.btnPascal.BackColor = Color.FromArgb(45, 52, 70); + + grpComb.Controls.Add(lblN); + grpComb.Controls.Add(numN); + grpComb.Controls.Add(lblR); + grpComb.Controls.Add(numR); + grpComb.Controls.Add(btnCalcComb); + grpComb.Controls.Add(btnPascal); + + // Group 2: Strings + StyleGroupBox(grpStrings, "2. Karakter Kombinasyon Üreteci", new Point(12, 190), new Size(350, 115)); + StyleLabel(lblAlphabet, "Alfabe:", new Point(15, 24)); + this.txtAlphabet.Location = new Point(68, 21); + this.txtAlphabet.Size = new Size(110, 23); + this.txtAlphabet.BackColor = Color.FromArgb(40, 43, 56); + this.txtAlphabet.ForeColor = Color.White; + this.txtAlphabet.BorderStyle = BorderStyle.FixedSingle; + this.txtAlphabet.Text = "ABC"; + + StyleLabel(lblLength, "Boyut:", new Point(190, 24)); + ((System.ComponentModel.ISupportInitialize)(this.numLength)).BeginInit(); + this.numLength.Location = new Point(238, 21); + this.numLength.Minimum = 1; + this.numLength.Maximum = 6; + this.numLength.Value = 3; + this.numLength.Size = new Size(45, 23); + this.numLength.BackColor = Color.FromArgb(40, 43, 56); + this.numLength.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numLength)).EndInit(); + + StyleLabel(lblPrefix, "Önek:", new Point(15, 52)); + this.txtPrefix.Location = new Point(68, 49); + this.txtPrefix.Size = new Size(110, 23); + this.txtPrefix.BackColor = Color.FromArgb(40, 43, 56); + this.txtPrefix.ForeColor = Color.White; + this.txtPrefix.BorderStyle = BorderStyle.FixedSingle; + this.txtPrefix.Text = ""; + + StyleActionBtn(btnGenStrings, "Dizilimleri Üret", new Point(190, 48), new Size(145, 25)); + this.btnGenStrings.BackColor = Color.FromArgb(45, 95, 80); + + grpStrings.Controls.Add(lblAlphabet); + grpStrings.Controls.Add(txtAlphabet); + grpStrings.Controls.Add(lblLength); + grpStrings.Controls.Add(numLength); + grpStrings.Controls.Add(lblPrefix); + grpStrings.Controls.Add(txtPrefix); + grpStrings.Controls.Add(btnGenStrings); + + // Group 3: Polar & Vector + StyleGroupBox(grpPolar, "3. Kutupsal (Polar) & Atan2 / Hipotenüs", new Point(12, 312), new Size(350, 95)); + StyleLabel(lblCoordX, "X:", new Point(15, 24)); + this.txtCoordX.Location = new Point(36, 21); + this.txtCoordX.Size = new Size(80, 23); + this.txtCoordX.BackColor = Color.FromArgb(40, 43, 56); + this.txtCoordX.ForeColor = Color.White; + this.txtCoordX.BorderStyle = BorderStyle.FixedSingle; + this.txtCoordX.Text = "3"; + + StyleLabel(lblCoordY, "Y:", new Point(130, 24)); + this.txtCoordY.Location = new Point(152, 21); + this.txtCoordY.Size = new Size(80, 23); + this.txtCoordY.BackColor = Color.FromArgb(40, 43, 56); + this.txtCoordY.ForeColor = Color.White; + this.txtCoordY.BorderStyle = BorderStyle.FixedSingle; + this.txtCoordY.Text = "4"; + + StyleActionBtn(btnPolarConvert, "(r, θ) ve Hipotenüs Hesapla", new Point(15, 54), new Size(320, 26)); + + grpPolar.Controls.Add(lblCoordX); + grpPolar.Controls.Add(txtCoordX); + grpPolar.Controls.Add(lblCoordY); + grpPolar.Controls.Add(txtCoordY); + grpPolar.Controls.Add(btnPolarConvert); + + // Group 4: Special Functions + StyleGroupBox(grpSpecial, "4. Hiperbolik, Ters Trig & Özel Logaritma", new Point(12, 414), new Size(350, 105)); + StyleLabel(lblSpecialX, "x:", new Point(15, 24)); + this.txtSpecialX.Location = new Point(36, 21); + this.txtSpecialX.Size = new Size(80, 23); + this.txtSpecialX.BackColor = Color.FromArgb(40, 43, 56); + this.txtSpecialX.ForeColor = Color.White; + this.txtSpecialX.BorderStyle = BorderStyle.FixedSingle; + this.txtSpecialX.Text = "0.75"; + + StyleLabel(lblBase, "Taban b:", new Point(130, 24)); + this.txtBase.Location = new Point(188, 21); + this.txtBase.Size = new Size(50, 23); + this.txtBase.BackColor = Color.FromArgb(40, 43, 56); + this.txtBase.ForeColor = Color.White; + this.txtBase.BorderStyle = BorderStyle.FixedSingle; + this.txtBase.Text = "2"; + + StyleActionBtn(btnSpecialCalc, "sinh, cosh, asin, acos, atan, log Hesapla", new Point(15, 54), new Size(320, 26)); + this.btnSpecialCalc.BackColor = Color.FromArgb(50, 110, 190); + + grpSpecial.Controls.Add(lblSpecialX); + grpSpecial.Controls.Add(txtSpecialX); + grpSpecial.Controls.Add(lblBase); + grpSpecial.Controls.Add(txtBase); + grpSpecial.Controls.Add(btnSpecialCalc); + + this.pnlLeft.Controls.Add(this.lblTitle); + this.pnlLeft.Controls.Add(this.lblDesc); + this.pnlLeft.Controls.Add(this.grpComb); + this.pnlLeft.Controls.Add(this.grpStrings); + this.pnlLeft.Controls.Add(this.grpPolar); + this.pnlLeft.Controls.Add(this.grpSpecial); + + this.txtOutput.Dock = DockStyle.Fill; + this.txtOutput.BackColor = Color.FromArgb(18, 19, 25); + this.txtOutput.ForeColor = Color.FromArgb(225, 232, 245); + this.txtOutput.Font = new Font("Consolas", 10F); + this.txtOutput.BorderStyle = BorderStyle.None; + this.txtOutput.ReadOnly = true; + + this.pnlRightHeader = new Panel { Dock = DockStyle.Top, Height = 34, BackColor = Color.FromArgb(24, 25, 32) }; + this.lblOutputTitle = new Label + { + Text = "📊 Hesaplama Sonuç Raporu:", + Dock = DockStyle.Left, + Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold), + ForeColor = ThemeHelper.LightText, + TextAlign = ContentAlignment.MiddleLeft + }; + this.btnCopyOutput = new Button + { + Text = "📋 Kopyala", + Dock = DockStyle.Right, + Width = 90, + FlatStyle = FlatStyle.Flat, + BackColor = ThemeHelper.ButtonSecondary, + ForeColor = Color.White, + Font = new Font("Segoe UI", 8.5F), + Cursor = Cursors.Hand + }; + this.btnCopyOutput.FlatAppearance.BorderSize = 0; + + this.pnlRightHeader.Controls.Add(this.lblOutputTitle); + this.pnlRightHeader.Controls.Add(this.btnCopyOutput); + + Panel pnlRight = new Panel { Dock = DockStyle.Fill, Padding = new Padding(12, 0, 0, 0) }; + pnlRight.Controls.Add(this.txtOutput); + pnlRight.Controls.Add(this.pnlRightHeader); + + this.Controls.Add(pnlRight); + this.Controls.Add(this.pnlLeft); + this.ResumeLayout(false); + } + + private void StyleGroupBox(GroupBox g, string text, Point loc, Size sz) + { + g.Text = text; + g.Location = loc; + g.Size = sz; + g.ForeColor = Color.FromArgb(160, 210, 255); + g.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + } + + private void StyleLabel(Label l, string text, Point loc) + { + l.Text = text; + l.Location = loc; + l.AutoSize = true; + l.ForeColor = Color.FromArgb(200, 210, 230); + l.Font = new Font("Segoe UI", 8.5F); + } + + private void StyleActionBtn(Button b, string text, Point loc, Size sz) + { + b.Text = text; + b.Location = loc; + b.Size = sz; + b.BackColor = Color.FromArgb(46, 125, 225); + b.ForeColor = Color.White; + b.FlatStyle = FlatStyle.Flat; + b.FlatAppearance.BorderSize = 0; + b.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + b.Cursor = Cursors.Hand; + } + } +} diff --git a/MathApp/MathApp/Controls/CombinatoricsControl.cs b/MathApp/MathApp/Controls/CombinatoricsControl.cs new file mode 100644 index 0000000..2d44af0 --- /dev/null +++ b/MathApp/MathApp/Controls/CombinatoricsControl.cs @@ -0,0 +1,268 @@ +using System; +using System.Drawing; +using System.Globalization; +using System.Text; +using System.Windows.Forms; +using DotNetMatrix; + +namespace MathApp.Controls +{ + public partial class CombinatoricsControl : UserControl + { + public CombinatoricsControl() + { + InitializeComponent(); + + btnCalcComb.Click += BtnCalcComb_Click; + btnPascal.Click += BtnPascal_Click; + btnGenStrings.Click += BtnGenStrings_Click; + btnPolarConvert.Click += BtnPolarConvert_Click; + btnSpecialCalc.Click += BtnSpecialCalc_Click; + + btnCopyOutput.Click += (s, e) => { + if (!string.IsNullOrEmpty(txtOutput.Text)) + { + Clipboard.SetText(txtOutput.Text); + MessageBox.Show("Sonuç raporu panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + txtCoordX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPolarConvert_Click(this, EventArgs.Empty); } }; + txtCoordY.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPolarConvert_Click(this, EventArgs.Empty); } }; + txtSpecialX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnSpecialCalc_Click(this, EventArgs.Empty); } }; + txtBase.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnSpecialCalc_Click(this, EventArgs.Empty); } }; + txtAlphabet.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnGenStrings_Click(this, EventArgs.Empty); } }; + } + + private void BtnCalcComb_Click(object sender, EventArgs e) + { + try + { + int n = (int)numN.Value; + int r = (int)numR.Value; + + if (r > n) + { + txtOutput.Text = "Hata: r (k) değeri n değerinden büyük olamaz!"; + return; + } + + string factNStr = n <= 27 ? NumericalMethods.Factorial(n).ToString("N0") : $"{n}! (decimal sınırını aşıyor: > 7.9×10²⁸)"; + string factRStr = r <= 27 ? NumericalMethods.Factorial(r).ToString("N0") : $"{r}! (decimal sınırını aşıyor: > 7.9×10²⁸)"; + decimal perm = NumericalMethods.Permutation(n, r); + decimal comb = NumericalMethods.Combination(n, r); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("=== KOMBINATORIK & PERMUTASYON HESABI ==="); + sb.AppendLine($"n = {n}, r (k) = {r}"); + sb.AppendLine(); + sb.AppendLine($"1. Faktöriyel n! :"); + sb.AppendLine($" {factNStr}"); + sb.AppendLine(); + sb.AppendLine($"2. Faktöriyel r! :"); + sb.AppendLine($" {factRStr}"); + sb.AppendLine(); + sb.AppendLine($"3. Permütasyon P(n, r) = n! / (n - r)! :"); + sb.AppendLine($" P({n}, {r}) = {perm:N0}"); + sb.AppendLine(); + sb.AppendLine($"4. Kombinasyon C(n, r) = n! / [r! * (n - r)!] :"); + sb.AppendLine($" C({n}, {r}) = {comb:N0}"); + sb.AppendLine(); + sb.AppendLine($"Olasılık Bilgisi:"); + sb.AppendLine($" {n} elemanlı bir kümeden {r} eleman {comb:N0} farklı şekilde seçilebilir."); + sb.AppendLine($" Sıralı seçim (dizilim) sayısı ise {perm:N0}'dir."); + + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + txtOutput.Text = "Hesaplama Hatası: " + ex.Message; + } + } + + private void BtnPascal_Click(object sender, EventArgs e) + { + 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++) + { + 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(); + } + + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + txtOutput.Text = "Hata: " + ex.Message; + } + } + + private void BtnGenStrings_Click(object sender, EventArgs e) + { + try + { + string alphabet = txtAlphabet.Text; + string prefix = txtPrefix.Text; + int length = (int)numLength.Value; + + if (string.IsNullOrEmpty(alphabet)) + { + txtOutput.Text = "Lütfen karakter kümesini (alfabe) giriniz."; + return; + } + + long totalCount = (long)Math.Pow(alphabet.Length, length); + if (totalCount > 20000) + { + DialogResult dr = MessageBox.Show( + $"Üretilecek toplam kombinasyon sayısı {totalCount:N0}. " + + "Bu işlem arayüzü yavaşlatabilir. Devam etmek istiyor musunuz?", + "Büyük Kombinasyon Uyarısı", + MessageBoxButtons.YesNo, + MessageBoxIcon.Warning); + + if (dr != DialogResult.Yes) return; + } + + string generated = NumericalMethods.GenerateCombinations(alphabet, prefix, length); + + 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); + + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + txtOutput.Text = "Kombinasyon Üretim Hatası: " + ex.Message; + } + } + + private void BtnPolarConvert_Click(object sender, EventArgs e) + { + try + { + if (!decimal.TryParse(txtCoordX.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal x) || + !decimal.TryParse(txtCoordY.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal y)) + { + txtOutput.Text = "Lütfen geçerli X ve Y sayısal koordinatları giriniz."; + return; + } + + // Maths.Hypot and DecimalMath.Atan2 + decimal rHypot = Maths.Hypot(x, y); + decimal r = DecimalMath.Sqrt(x * x + y * y); + decimal thetaRad = DecimalMath.Atan2(y, x); + decimal thetaDeg = thetaRad * (180m / DecimalMath.PI); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("=== 2B VEKTOR & KUTUPSAL (POLAR) KOORDINAT HESABI ==="); + sb.AppendLine($"Kartezyen Koordinatlar : X = {x}, Y = {y}"); + sb.AppendLine(); + sb.AppendLine($"1. Hipotenüs / Yarıçap (r) = sqrt(X² + Y²):"); + sb.AppendLine($" r (DecimalMath) = {r:G18}"); + sb.AppendLine($" r (Maths.Hypot) = {rHypot:G18}"); + sb.AppendLine(); + sb.AppendLine($"2. Açı θ = Atan2(Y, X):"); + sb.AppendLine($" θ (Radyan) = {thetaRad:G18} rad"); + sb.AppendLine($" θ (Derece) = {thetaDeg:G18}°"); + sb.AppendLine(); + sb.AppendLine($"Kutupsal Gösterim : (r = {r:G8}, θ = {thetaDeg:F4}°)"); + + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + txtOutput.Text = "Koordinat Dönüşüm Hatası: " + ex.Message; + } + } + + private void BtnSpecialCalc_Click(object sender, EventArgs e) + { + try + { + if (!decimal.TryParse(txtSpecialX.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out decimal x)) + { + txtOutput.Text = "Lütfen x için geçerli bir sayı giriniz."; + return; + } + + decimal baseN = 2m; + if (!string.IsNullOrWhiteSpace(txtBase.Text)) + { + decimal.TryParse(txtBase.Text.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out baseN); + } + + StringBuilder sb = new StringBuilder(); + sb.AppendLine($"=== OZEL FONKSIYON HESAPLAMALARI (x = {x}) ==="); + sb.AppendLine(); + + // Hiperbolik Fonksiyonlar + sb.AppendLine("-- Hiperbolik Fonksiyonlar --"); + try { sb.AppendLine($" sinh(x) = {DecimalMath.Sinh(x):G16}"); } catch (Exception ex) { sb.AppendLine($" sinh(x): {ex.Message}"); } + try { sb.AppendLine($" cosh(x) = {DecimalMath.Cosh(x):G16}"); } catch (Exception ex) { sb.AppendLine($" cosh(x): {ex.Message}"); } + try { sb.AppendLine($" tanh(x) = {DecimalMath.Tanh(x):G16}"); } catch (Exception ex) { sb.AppendLine($" tanh(x): {ex.Message}"); } + sb.AppendLine(); + + // Ters Trigonometrik + sb.AppendLine("-- Ters Trigonometrik Fonksiyonlar --"); + if (Math.Abs(x) <= 1m) + { + try { sb.AppendLine($" asin(x) = {DecimalMath.Asin(x):G16} rad ({(DecimalMath.Asin(x) * 180m / DecimalMath.PI):F4}°)"); } catch { } + try { sb.AppendLine($" acos(x) = {DecimalMath.Acos(x):G16} rad ({(DecimalMath.Acos(x) * 180m / DecimalMath.PI):F4}°)"); } catch { } + } + else + { + sb.AppendLine(" asin(x) & acos(x): Tanımsız (|x| <= 1 olmalıdır)"); + } + try { sb.AppendLine($" atan(x) = {DecimalMath.Atan(x):G16} rad ({(DecimalMath.Atan(x) * 180m / DecimalMath.PI):F4}°)"); } catch { } + sb.AppendLine(); + + // Logaritmalar & Üs + sb.AppendLine("-- Üstel & Logaritmik --"); + try { sb.AppendLine($" exp(x) = e^{x} = {DecimalMath.Exp(x):G16}"); } catch (Exception ex) { sb.AppendLine($" exp(x): {ex.Message}"); } + if (x > 0m) + { + try { sb.AppendLine($" ln(x) = {DecimalMath.Log(x):G16}"); } catch { } + try { sb.AppendLine($" log10(x)= {DecimalMath.Log10(x):G16}"); } catch { } + if (baseN > 0m && baseN != 1m) + { + try + { + decimal logBaseN = DecimalMath.Log(x) / DecimalMath.Log(baseN); + sb.AppendLine($" log_{baseN}(x) = {logBaseN:G16}"); + } + catch { } + } + } + else + { + sb.AppendLine(" ln(x), log10(x): Tanımsız (x > 0 olmalıdır)"); + } + + txtOutput.Text = sb.ToString(); + } + catch (Exception ex) + { + txtOutput.Text = "Hata: " + ex.Message; + } + } + } +} diff --git a/MathApp/MathApp/Controls/DerivativeCalculatorControl.Designer.cs b/MathApp/MathApp/Controls/DerivativeCalculatorControl.Designer.cs new file mode 100644 index 0000000..43bd54a --- /dev/null +++ b/MathApp/MathApp/Controls/DerivativeCalculatorControl.Designer.cs @@ -0,0 +1,331 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class DerivativeCalculatorControl + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Nümerik Türev & Kısmi Türev Stüdyosu (Differentiation)", + "Merkezi sonlu farklar matrisi, ileri binom ve geri farklar yöntemleriyle yüksek dereceli türev, kısmi türev ve gradyan (∇f) analizi."); + + this.pnlContent = new Panel(); + this.pnlTopSettings = new Panel(); + this.lblStepH = new Label(); + this.txtStepH = new TextBox(); + this.lblAcc = new Label(); + this.cmbAccuracy = new ComboBox(); + + this.grpSingle = new GroupBox(); + this.lblSingleFn = new Label(); + this.txtSingleFn = new TextBox(); + this.lblSingleVar = new Label(); + this.txtSingleVar = new TextBox(); + this.lblSinglePoint = new Label(); + this.txtSinglePoint = new TextBox(); + this.lblSingleDeg = new Label(); + this.numSingleDegree = new NumericUpDown(); + this.btnCalcSingle = ThemeHelper.CreateActionButton("∂ Tek Değişkenli Türev", 190, 34, true); + this.btnExSingle1 = ThemeHelper.CreateExampleChip("Örnek: sin(x)+x³"); + this.btnExSingle2 = ThemeHelper.CreateExampleChip("Örnek: exp(2x)"); + + this.grpPartial = new GroupBox(); + this.lblPartialFn = new Label(); + this.txtPartialFn = new TextBox(); + this.lblTargetVar = new Label(); + this.txtTargetVar = new TextBox(); + this.lblPartialDeg = new Label(); + this.numPartialDegree = new NumericUpDown(); + this.pnlPartialVars = new FlowLayoutPanel(); + this.btnAddVar = ThemeHelper.CreateActionButton("+ Değişken", 110, 28, false); + this.btnCalcPartial = ThemeHelper.CreateActionButton("∇ Kısmi Türev & Gradyan", 210, 34, true); + this.btnExPartial1 = ThemeHelper.CreateExampleChip("Örnek: x²y + sin(y)"); + this.btnExPartial2 = ThemeHelper.CreateExampleChip("Örnek: exp(x*y)"); + + this.lblResult = new Label(); + this.txtResult = new TextBox(); + + ((System.ComponentModel.ISupportInitialize)(this.numSingleDegree)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numPartialDegree)).BeginInit(); + this.pnlContent.SuspendLayout(); + this.pnlTopSettings.SuspendLayout(); + this.grpSingle.SuspendLayout(); + this.grpPartial.SuspendLayout(); + this.SuspendLayout(); + + this.pnlContent.Dock = DockStyle.Fill; + this.pnlContent.BackColor = ThemeHelper.DarkBackground; + this.pnlContent.Padding = new Padding(20, 12, 20, 20); + + // Top settings bar + this.pnlTopSettings.Dock = DockStyle.Top; + this.pnlTopSettings.Height = 38; + + this.lblStepH.Text = "Adım Boyutu (h):"; + this.lblStepH.AutoSize = true; + this.lblStepH.ForeColor = ThemeHelper.LightText; + this.lblStepH.Font = new Font("Segoe UI", 9.5F); + this.lblStepH.Location = new Point(4, 8); + + this.txtStepH.Location = new Point(115, 5); + this.txtStepH.Size = new Size(75, 25); + this.txtStepH.Text = "0.001"; + this.txtStepH.Font = new Font("Consolas", 10F); + this.txtStepH.BackColor = ThemeHelper.CardBackground; + this.txtStepH.ForeColor = Color.White; + this.txtStepH.BorderStyle = BorderStyle.FixedSingle; + + this.lblAcc.Text = "Matris Hassasiyet Derecesi:"; + this.lblAcc.AutoSize = true; + this.lblAcc.ForeColor = ThemeHelper.LightText; + this.lblAcc.Font = new Font("Segoe UI", 9.5F); + this.lblAcc.Location = new Point(215, 8); + + this.cmbAccuracy.Items.AddRange(new object[] { + "2. Derece O(h²)", + "4. Derece O(h⁴) - Önerilen", + "6. Derece O(h⁶) - Yüksek" + }); + this.cmbAccuracy.Location = new Point(385, 5); + this.cmbAccuracy.Size = new Size(200, 25); + this.cmbAccuracy.DropDownStyle = ComboBoxStyle.DropDownList; + this.cmbAccuracy.BackColor = ThemeHelper.CardBackground; + this.cmbAccuracy.ForeColor = Color.White; + this.cmbAccuracy.Font = new Font("Segoe UI", 9.5F); + + this.pnlTopSettings.Controls.Add(this.cmbAccuracy); + this.pnlTopSettings.Controls.Add(this.lblAcc); + this.pnlTopSettings.Controls.Add(this.txtStepH); + this.pnlTopSettings.Controls.Add(this.lblStepH); + + // grpSingle + this.grpSingle.Location = new Point(20, 54); + this.grpSingle.Size = new Size(405, 225); + this.grpSingle.ForeColor = ThemeHelper.LightText; + this.grpSingle.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.grpSingle.Text = "1. Tek Değişkenli Türev: dⁿf(x) / dxⁿ"; + + this.lblSingleFn.Text = "f(x) ="; + this.lblSingleFn.AutoSize = true; + this.lblSingleFn.Location = new Point(14, 30); + this.txtSingleFn.Location = new Point(75, 27); + this.txtSingleFn.Size = new Size(310, 26); + this.txtSingleFn.Text = "sin(x) + x^3"; + this.txtSingleFn.Font = new Font("Consolas", 10.5F); + this.txtSingleFn.BackColor = ThemeHelper.CardBackground; + this.txtSingleFn.ForeColor = Color.White; + this.txtSingleFn.BorderStyle = BorderStyle.FixedSingle; + + this.lblSingleVar.Text = "Değişken:"; + this.lblSingleVar.AutoSize = true; + this.lblSingleVar.Location = new Point(14, 68); + this.txtSingleVar.Location = new Point(85, 65); + this.txtSingleVar.Size = new Size(50, 26); + this.txtSingleVar.Text = "x"; + this.txtSingleVar.Font = new Font("Consolas", 10.5F); + this.txtSingleVar.BackColor = ThemeHelper.CardBackground; + this.txtSingleVar.ForeColor = Color.White; + this.txtSingleVar.BorderStyle = BorderStyle.FixedSingle; + + this.lblSinglePoint.Text = "Nokta (x₀):"; + this.lblSinglePoint.AutoSize = true; + this.lblSinglePoint.Location = new Point(150, 68); + this.txtSinglePoint.Location = new Point(230, 65); + this.txtSinglePoint.Size = new Size(65, 26); + this.txtSinglePoint.Text = "1"; + this.txtSinglePoint.Font = new Font("Consolas", 10.5F); + this.txtSinglePoint.BackColor = ThemeHelper.CardBackground; + this.txtSinglePoint.ForeColor = Color.White; + this.txtSinglePoint.BorderStyle = BorderStyle.FixedSingle; + + this.lblSingleDeg.Text = "Türev Derecesi:"; + this.lblSingleDeg.AutoSize = true; + this.lblSingleDeg.Location = new Point(14, 106); + this.numSingleDegree.Location = new Point(120, 104); + this.numSingleDegree.Size = new Size(60, 26); + this.numSingleDegree.Minimum = 1; + this.numSingleDegree.Maximum = 6; + this.numSingleDegree.Value = 1; + this.numSingleDegree.Font = new Font("Consolas", 10.5F); + this.numSingleDegree.BackColor = ThemeHelper.CardBackground; + this.numSingleDegree.ForeColor = Color.White; + this.numSingleDegree.BorderStyle = BorderStyle.FixedSingle; + + this.btnCalcSingle.Location = new Point(195, 100); + this.btnExSingle1.Location = new Point(14, 155); + this.btnExSingle2.Location = new Point(165, 155); + + this.grpSingle.Controls.Add(this.btnExSingle2); + this.grpSingle.Controls.Add(this.btnExSingle1); + this.grpSingle.Controls.Add(this.btnCalcSingle); + this.grpSingle.Controls.Add(this.numSingleDegree); + this.grpSingle.Controls.Add(this.lblSingleDeg); + this.grpSingle.Controls.Add(this.txtSinglePoint); + this.grpSingle.Controls.Add(this.lblSinglePoint); + this.grpSingle.Controls.Add(this.txtSingleVar); + this.grpSingle.Controls.Add(this.lblSingleVar); + this.grpSingle.Controls.Add(this.txtSingleFn); + this.grpSingle.Controls.Add(this.lblSingleFn); + + // grpPartial + this.grpPartial.Location = new Point(440, 54); + this.grpPartial.Size = new Size(440, 225); + this.grpPartial.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.grpPartial.ForeColor = ThemeHelper.LightText; + this.grpPartial.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.grpPartial.Text = "2. Çok Değişkenli Kısmi Türev & Gradyan (∂ⁿf / ∂xᵢⁿ)"; + + this.lblPartialFn.Text = "f(...) ="; + this.lblPartialFn.AutoSize = true; + this.lblPartialFn.Location = new Point(14, 28); + this.txtPartialFn.Location = new Point(65, 25); + this.txtPartialFn.Size = new Size(195, 26); + this.txtPartialFn.Text = "x^2*y + sin(y)"; + this.txtPartialFn.Font = new Font("Consolas", 10F); + this.txtPartialFn.BackColor = ThemeHelper.CardBackground; + this.txtPartialFn.ForeColor = Color.White; + this.txtPartialFn.BorderStyle = BorderStyle.FixedSingle; + + this.lblTargetVar.Text = "Türev Değişkeni:"; + this.lblTargetVar.AutoSize = true; + this.lblTargetVar.Location = new Point(268, 28); + this.txtTargetVar.Location = new Point(378, 25); + this.txtTargetVar.Size = new Size(45, 26); + this.txtTargetVar.Text = "x"; + this.txtTargetVar.Font = new Font("Consolas", 10F, FontStyle.Bold); + this.txtTargetVar.BackColor = ThemeHelper.CardBackground; + this.txtTargetVar.ForeColor = Color.FromArgb(56, 189, 248); + this.txtTargetVar.BorderStyle = BorderStyle.FixedSingle; + this.txtTargetVar.TextAlign = HorizontalAlignment.Center; + + this.pnlPartialVars.Location = new Point(14, 58); + this.pnlPartialVars.Size = new Size(410, 110); + this.pnlPartialVars.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPartialVars.AutoScroll = true; + this.pnlPartialVars.BackColor = Color.FromArgb(11, 17, 32); + + this.lblPartialDeg.Text = "Derece:"; + this.lblPartialDeg.AutoSize = true; + this.lblPartialDeg.Location = new Point(14, 182); + this.numPartialDegree.Location = new Point(68, 179); + this.numPartialDegree.Size = new Size(48, 26); + this.numPartialDegree.Minimum = 1; + this.numPartialDegree.Maximum = 4; + this.numPartialDegree.Value = 1; + this.numPartialDegree.BackColor = ThemeHelper.CardBackground; + this.numPartialDegree.ForeColor = Color.White; + this.numPartialDegree.BorderStyle = BorderStyle.FixedSingle; + + this.btnAddVar.Location = new Point(122, 178); + this.btnCalcPartial.Location = new Point(238, 175); + + this.grpPartial.Controls.Add(this.btnCalcPartial); + this.grpPartial.Controls.Add(this.btnAddVar); + this.grpPartial.Controls.Add(this.numPartialDegree); + this.grpPartial.Controls.Add(this.lblPartialDeg); + this.grpPartial.Controls.Add(this.pnlPartialVars); + this.grpPartial.Controls.Add(this.txtTargetVar); + this.grpPartial.Controls.Add(this.lblTargetVar); + this.grpPartial.Controls.Add(this.txtPartialFn); + this.grpPartial.Controls.Add(this.lblPartialFn); + + // Result area + this.lblResult.Text = "📊 Nümerik Türev, Kısmi Türev ve Gradyan Raporu:"; + this.lblResult.AutoSize = true; + this.lblResult.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold); + this.lblResult.ForeColor = ThemeHelper.LightText; + this.lblResult.Location = new Point(20, 290); + + this.btnCopyDerivative = ThemeHelper.CreateCopyButton("📋 Kopyala"); + this.btnCopyDerivative.Location = new Point(780, 284); + this.btnCopyDerivative.Anchor = AnchorStyles.Top | AnchorStyles.Right; + + this.txtResult.Location = new Point(20, 316); + this.txtResult.Size = new Size(860, 245); + this.txtResult.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + this.txtResult.Multiline = true; + this.txtResult.ReadOnly = true; + this.txtResult.ScrollBars = ScrollBars.Vertical; + this.txtResult.BackColor = ThemeHelper.CardBackground; + this.txtResult.ForeColor = Color.FromArgb(186, 230, 253); + this.txtResult.BorderStyle = BorderStyle.FixedSingle; + this.txtResult.Font = new Font("Consolas", 10F); + + this.pnlContent.Controls.Add(this.btnCopyDerivative); + this.pnlContent.Controls.Add(this.txtResult); + this.pnlContent.Controls.Add(this.lblResult); + this.pnlContent.Controls.Add(this.grpPartial); + this.pnlContent.Controls.Add(this.grpSingle); + this.pnlContent.Controls.Add(this.pnlTopSettings); + + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.pnlContent); + this.Controls.Add(this.pnlHeader); + this.Name = "DerivativeCalculatorControl"; + this.Size = new Size(900, 660); + + ((System.ComponentModel.ISupportInitialize)(this.numSingleDegree)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numPartialDegree)).EndInit(); + this.pnlTopSettings.ResumeLayout(false); + this.pnlTopSettings.PerformLayout(); + this.grpSingle.ResumeLayout(false); + this.grpSingle.PerformLayout(); + this.grpPartial.ResumeLayout(false); + this.grpPartial.PerformLayout(); + this.pnlContent.ResumeLayout(false); + this.pnlContent.PerformLayout(); + this.ResumeLayout(false); + } + + private Panel pnlHeader; + private Panel pnlContent; + private Panel pnlTopSettings; + private Label lblStepH; + private TextBox txtStepH; + private Label lblAcc; + private ComboBox cmbAccuracy; + private GroupBox grpSingle; + private Label lblSingleFn; + private TextBox txtSingleFn; + private Label lblSingleVar; + private TextBox txtSingleVar; + private Label lblSinglePoint; + private TextBox txtSinglePoint; + private Label lblSingleDeg; + private NumericUpDown numSingleDegree; + private Button btnCalcSingle; + private Button btnExSingle1; + private Button btnExSingle2; + private GroupBox grpPartial; + private Label lblPartialFn; + private TextBox txtPartialFn; + private Label lblTargetVar; + private TextBox txtTargetVar; + private Label lblPartialDeg; + private NumericUpDown numPartialDegree; + private FlowLayoutPanel pnlPartialVars; + private Button btnAddVar; + private Button btnCalcPartial; + private Button btnExPartial1; + private Button btnExPartial2; + private Label lblResult; + private Button btnCopyDerivative; + private TextBox txtResult; + } +} diff --git a/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs b/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs new file mode 100644 index 0000000..5c7736c --- /dev/null +++ b/MathApp/MathApp/Controls/DerivativeCalculatorControl.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + public partial class DerivativeCalculatorControl : UserControl + { + private List partialRows = new List(); + + public DerivativeCalculatorControl() + { + InitializeComponent(); + + cmbAccuracy.SelectedIndex = 1; // 4th order default + btnCalcSingle.Click += BtnCalcSingle_Click; + btnAddVar.Click += BtnAddVar_Click; + btnCalcPartial.Click += BtnCalcPartial_Click; + + btnCopyDerivative.Click += (s, e) => { + if (!string.IsNullOrEmpty(txtResult.Text)) + { + Clipboard.SetText(txtResult.Text); + MessageBox.Show("Türev raporu panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + btnExSingle1.Click += (s, e) => { + txtSingleFn.Text = "sin(x) + x^3"; + txtSingleVar.Text = "x"; + txtSinglePoint.Text = "1"; + numSingleDegree.Value = 1; + BtnCalcSingle_Click(this, EventArgs.Empty); + }; + btnExSingle2.Click += (s, e) => { + txtSingleFn.Text = "exp(2*x)"; + txtSingleVar.Text = "x"; + txtSinglePoint.Text = "0"; + numSingleDegree.Value = 3; + BtnCalcSingle_Click(this, EventArgs.Empty); + }; + + btnExPartial1.Click += (s, e) => LoadPartialPreset("x^2*y + sin(y)", "x", 1, new[] { ("x", "2"), ("y", "1") }); + btnExPartial2.Click += (s, e) => LoadPartialPreset("exp(x*y) + x^3*y^2", "x", 2, new[] { ("x", "1"), ("y", "1") }); + + AddPartialRow("x", "1"); + AddPartialRow("y", "2"); + } + + private void LoadPartialPreset(string eq, string targetVar, int degree, (string v, string val)[] vars) + { + txtPartialFn.Text = eq; + txtTargetVar.Text = targetVar; + numPartialDegree.Value = degree; + pnlPartialVars.Controls.Clear(); + partialRows.Clear(); + foreach (var item in vars) + { + AddPartialRow(item.v, item.val); + } + BtnCalcPartial_Click(this, EventArgs.Empty); + } + + private void BtnAddVar_Click(object sender, EventArgs e) + { + string[] names = { "x", "y", "z", "w", "u", "v" }; + string suggested = partialRows.Count < names.Length ? names[partialRows.Count] : "v" + (partialRows.Count + 1); + AddPartialRow(suggested, "1"); + } + + private void AddPartialRow(string varName, string val) + { + VariableInputRow row = new VariableInputRow(varName, val); + row.OnRemove += (s, e) => + { + pnlPartialVars.Controls.Remove(row.Panel); + partialRows.Remove(row); + }; + pnlPartialVars.Controls.Add(row.Panel); + partialRows.Add(row); + } + + private decimal ParseDec(string s, string field) + { + string norm = (s ?? "").Trim().Replace(',', '.'); + if (decimal.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal v)) + return v; + throw new ArgumentException($"'{field}' için geçerli bir sayı giriniz."); + } + + private void BtnCalcSingle_Click(object sender, EventArgs e) + { + try + { + string eq = txtSingleFn.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) return; + + string v = string.IsNullOrWhiteSpace(txtSingleVar.Text) ? "x" : txtSingleVar.Text.Trim(); + decimal pt = ParseDec(txtSinglePoint.Text, "Nokta (x₀)"); + decimal h = ParseDec(txtStepH.Text, "Adım Boyutu (h)"); + int deg = (int)numSingleDegree.Value; + int acc = (cmbAccuracy.SelectedIndex + 1) * 2; // 2, 4, 6 + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + 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++) + { + 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)}"); + } + + txtResult.Text = sb.ToString(); + } + finally + { + Function.UseRadians = prevRad; + } + } + catch (Exception ex) + { + txtResult.Text = "❌ Hata: " + ex.Message; + } + } + + private void BtnCalcPartial_Click(object sender, EventArgs e) + { + try + { + string eq = txtPartialFn.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) return; + + string targetVar = txtTargetVar.Text.Trim(); + int deg = (int)numPartialDegree.Value; + decimal h = ParseDec(txtStepH.Text, "Adım Boyutu (h)"); + int acc = (cmbAccuracy.SelectedIndex + 1) * 2; + + Dictionary pts = new Dictionary(); + foreach (var row in partialRows) + { + if (string.IsNullOrWhiteSpace(row.Variable)) continue; + pts[row.Variable] = ParseDec(row.Value, row.Variable); + } + + if (!pts.ContainsKey(targetVar)) + { + txtResult.Text = $"⚠️ Hedef değişken '{targetVar}', değişken listesinde tanımlı olmalıdır."; + return; + } + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + 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) + { + 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)} ]"); + + txtResult.Text = sb.ToString(); + } + finally + { + Function.UseRadians = prevRad; + } + } + catch (Exception ex) + { + txtResult.Text = "❌ Hata: " + ex.Message; + } + } + } +} diff --git a/MathApp/MathApp/Controls/GraphPlotterControl.Designer.cs b/MathApp/MathApp/Controls/GraphPlotterControl.Designer.cs index 080ccf5..84c08b6 100644 --- a/MathApp/MathApp/Controls/GraphPlotterControl.Designer.cs +++ b/MathApp/MathApp/Controls/GraphPlotterControl.Designer.cs @@ -1,3 +1,6 @@ +using System; +using System.Drawing; +using System.Windows.Forms; namespace MathApp.Controls { @@ -16,159 +19,172 @@ namespace MathApp.Controls private void InitializeComponent() { - this.lblTitle = new System.Windows.Forms.Label(); - this.pnlControls = new System.Windows.Forms.Panel(); - this.pnlGraphConfig = new System.Windows.Forms.Panel(); - this.pnlCanvas = new System.Windows.Forms.Panel(); - - this.lblEquation = new System.Windows.Forms.Label(); - this.txtEquation = new System.Windows.Forms.TextBox(); - this.lblMinX = new System.Windows.Forms.Label(); - this.txtMinX = new System.Windows.Forms.TextBox(); - this.lblMaxX = new System.Windows.Forms.Label(); - this.txtMaxX = new System.Windows.Forms.TextBox(); - this.btnPlot = new System.Windows.Forms.Button(); + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Etkileşimli Fonksiyon Grafiği Çizici (Graph Plotter)", + "Gerçek zamanlı yakınlaştırma (Zoom), kaydırma (Pan), asimptot algılama ve eğri üzerinde koordinat inceleme."); + + this.pnlControls = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnEx1 = ThemeHelper.CreateExampleChip("sin(x) * x"); + this.btnEx2 = ThemeHelper.CreateExampleChip("x³ - 3x"); + this.btnEx3 = ThemeHelper.CreateExampleChip("e^(-x²/4)*cos(2x)"); + this.btnEx4 = ThemeHelper.CreateExampleChip("1 / (x² - 1)"); + + this.lblEquation = new Label(); + this.txtEquation = new TextBox(); + this.lblMinX = new Label(); + this.txtMinX = new TextBox(); + this.lblMaxX = new Label(); + this.txtMaxX = new TextBox(); + this.btnPlot = ThemeHelper.CreateActionButton("📈 Grafiği Çiz", 130, 32, true); + this.btnResetView = ThemeHelper.CreateActionButton("🔄 Sıfırla", 100, 32, false); + this.btnClearMarks = ThemeHelper.CreateActionButton("📍 Noktaları Sil", 130, 32, false); + + this.pnlStatusBar = new Panel(); + this.lblStatus = new Label(); + this.pnlCanvas = new Panel(); this.pnlControls.SuspendLayout(); - this.pnlGraphConfig.SuspendLayout(); + this.pnlStatusBar.SuspendLayout(); this.SuspendLayout(); - // - // lblTitle - // - this.lblTitle.Dock = System.Windows.Forms.DockStyle.Top; - this.lblTitle.Font = new System.Drawing.Font("Segoe UI Light", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.lblTitle.ForeColor = System.Drawing.Color.White; - this.lblTitle.Location = new System.Drawing.Point(0, 0); - this.lblTitle.Name = "lblTitle"; - this.lblTitle.Size = new System.Drawing.Size(800, 60); - this.lblTitle.TabIndex = 0; - this.lblTitle.Text = "Graph Plotter"; - this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - - // // pnlControls - // - this.pnlControls.Controls.Add(this.pnlGraphConfig); - this.pnlControls.Dock = System.Windows.Forms.DockStyle.Top; - this.pnlControls.Location = new System.Drawing.Point(0, 60); - this.pnlControls.Name = "pnlControls"; - this.pnlControls.Size = new System.Drawing.Size(800, 80); - this.pnlControls.TabIndex = 1; + this.pnlControls.Dock = DockStyle.Top; + this.pnlControls.Height = 96; + this.pnlControls.BackColor = ThemeHelper.DarkBackground; + this.pnlControls.Padding = new Padding(24, 8, 24, 8); - // - // pnlGraphConfig - // - this.pnlGraphConfig.Controls.Add(this.btnPlot); - this.pnlGraphConfig.Controls.Add(this.txtMaxX); - this.pnlGraphConfig.Controls.Add(this.lblMaxX); - this.pnlGraphConfig.Controls.Add(this.txtMinX); - this.pnlGraphConfig.Controls.Add(this.lblMinX); - this.pnlGraphConfig.Controls.Add(this.txtEquation); - this.pnlGraphConfig.Controls.Add(this.lblEquation); - this.pnlGraphConfig.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlGraphConfig.Location = new System.Drawing.Point(0, 0); - this.pnlGraphConfig.Name = "pnlGraphConfig"; - this.pnlGraphConfig.Size = new System.Drawing.Size(800, 80); - this.pnlGraphConfig.TabIndex = 0; + this.lblPresets.Text = "Hızlı Fonksiyonlar:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 10, 0); - int xPos = 20; int yPos = 25; + this.pnlPresets.Location = new Point(24, 8); + this.pnlPresets.Size = new Size(820, 34); + this.pnlPresets.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnEx1); + this.pnlPresets.Controls.Add(this.btnEx2); + this.pnlPresets.Controls.Add(this.btnEx3); + this.pnlPresets.Controls.Add(this.btnEx4); + + int y = 52; - // Equation this.lblEquation.AutoSize = true; - this.lblEquation.ForeColor = System.Drawing.Color.White; - this.lblEquation.Text = "y = "; - this.lblEquation.Location = new System.Drawing.Point(xPos, yPos); - xPos += 30; - - this.txtEquation.Location = new System.Drawing.Point(xPos, yPos-3); - this.txtEquation.Size = new System.Drawing.Size(200, 23); - this.txtEquation.BackColor = System.Drawing.Color.FromArgb(40,40,40); - this.txtEquation.ForeColor = System.Drawing.Color.White; - this.txtEquation.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - xPos += 220; + this.lblEquation.ForeColor = ThemeHelper.LightText; + this.lblEquation.Font = new Font("Segoe UI Semibold", 10.5F, FontStyle.Bold); + this.lblEquation.Text = "f(x) ="; + this.lblEquation.Location = new Point(24, y + 3); + + this.txtEquation.Location = new Point(74, y); + this.txtEquation.Size = new Size(210, 27); + this.txtEquation.Text = "sin(x)"; + this.txtEquation.Font = new Font("Consolas", 11F); + this.txtEquation.BackColor = ThemeHelper.CardBackground; + this.txtEquation.ForeColor = Color.White; + this.txtEquation.BorderStyle = BorderStyle.FixedSingle; - // Min X this.lblMinX.AutoSize = true; - this.lblMinX.ForeColor = System.Drawing.Color.White; + this.lblMinX.ForeColor = ThemeHelper.LightText; + this.lblMinX.Font = new Font("Segoe UI", 9.5F); this.lblMinX.Text = "Min X:"; - this.lblMinX.Location = new System.Drawing.Point(xPos, yPos); - xPos += 50; - - this.txtMinX.Location = new System.Drawing.Point(xPos, yPos-3); - this.txtMinX.Size = new System.Drawing.Size(50, 23); + this.lblMinX.Location = new Point(296, y + 4); + + this.txtMinX.Location = new Point(344, y); + this.txtMinX.Size = new Size(55, 27); this.txtMinX.Text = "-10"; - this.txtMinX.BackColor = System.Drawing.Color.FromArgb(40,40,40); - this.txtMinX.ForeColor = System.Drawing.Color.White; - this.txtMinX.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - xPos += 70; + this.txtMinX.Font = new Font("Consolas", 10.5F); + this.txtMinX.BackColor = ThemeHelper.CardBackground; + this.txtMinX.ForeColor = Color.White; + this.txtMinX.BorderStyle = BorderStyle.FixedSingle; - // Max X this.lblMaxX.AutoSize = true; - this.lblMaxX.ForeColor = System.Drawing.Color.White; + this.lblMaxX.ForeColor = ThemeHelper.LightText; + this.lblMaxX.Font = new Font("Segoe UI", 9.5F); this.lblMaxX.Text = "Max X:"; - this.lblMaxX.Location = new System.Drawing.Point(xPos, yPos); - xPos += 50; + this.lblMaxX.Location = new Point(408, y + 4); - this.txtMaxX.Location = new System.Drawing.Point(xPos, yPos-3); - this.txtMaxX.Size = new System.Drawing.Size(50, 23); + this.txtMaxX.Location = new Point(458, y); + this.txtMaxX.Size = new Size(55, 27); this.txtMaxX.Text = "10"; - this.txtMaxX.BackColor = System.Drawing.Color.FromArgb(40,40,40); - this.txtMaxX.ForeColor = System.Drawing.Color.White; - this.txtMaxX.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - xPos += 70; + this.txtMaxX.Font = new Font("Consolas", 10.5F); + this.txtMaxX.BackColor = ThemeHelper.CardBackground; + this.txtMaxX.ForeColor = Color.White; + this.txtMaxX.BorderStyle = BorderStyle.FixedSingle; - // Plot Button - this.btnPlot.Location = new System.Drawing.Point(xPos, yPos-5); - this.btnPlot.Size = new System.Drawing.Size(100, 30); - this.btnPlot.Text = "Plot"; - this.btnPlot.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnPlot.BackColor = System.Drawing.Color.FromArgb(0, 120, 215); - this.btnPlot.ForeColor = System.Drawing.Color.White; - this.btnPlot.FlatAppearance.BorderSize = 0; + this.btnPlot.Location = new Point(525, y - 2); + this.btnResetView.Location = new Point(663, y - 2); + this.btnClearMarks.Location = new Point(771, y - 2); + this.pnlControls.Controls.Add(this.pnlPresets); + this.pnlControls.Controls.Add(this.btnClearMarks); + this.pnlControls.Controls.Add(this.btnResetView); + this.pnlControls.Controls.Add(this.btnPlot); + this.pnlControls.Controls.Add(this.txtMaxX); + this.pnlControls.Controls.Add(this.lblMaxX); + this.pnlControls.Controls.Add(this.txtMinX); + this.pnlControls.Controls.Add(this.lblMinX); + this.pnlControls.Controls.Add(this.txtEquation); + this.pnlControls.Controls.Add(this.lblEquation); + + // pnlStatusBar + this.pnlStatusBar.Dock = DockStyle.Bottom; + this.pnlStatusBar.Height = 28; + this.pnlStatusBar.BackColor = Color.FromArgb(11, 17, 32); + this.pnlStatusBar.Padding = new Padding(16, 4, 16, 4); + + this.lblStatus.Dock = DockStyle.Fill; + this.lblStatus.ForeColor = ThemeHelper.MutedText; + this.lblStatus.Font = new Font("Segoe UI", 9F); + this.lblStatus.TextAlign = ContentAlignment.MiddleLeft; + this.lblStatus.Text = "Hazır."; + this.pnlStatusBar.Controls.Add(this.lblStatus); - // // pnlCanvas - // - this.pnlCanvas.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlCanvas.Location = new System.Drawing.Point(0, 140); - this.pnlCanvas.Name = "pnlCanvas"; - this.pnlCanvas.Size = new System.Drawing.Size(800, 460); - this.pnlCanvas.TabIndex = 2; - this.pnlCanvas.BackColor = System.Drawing.Color.FromArgb(30, 30, 30); - this.pnlCanvas.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlCanvas_Paint); - this.pnlCanvas.Resize += new System.EventHandler(this.pnlCanvas_Resize); + this.pnlCanvas.Dock = DockStyle.Fill; + this.pnlCanvas.BackColor = Color.FromArgb(11, 17, 32); + this.pnlCanvas.Cursor = Cursors.Cross; + this.pnlCanvas.Paint += new PaintEventHandler(this.pnlCanvas_Paint); + this.pnlCanvas.Resize += new EventHandler(this.pnlCanvas_Resize); - // // GraphPlotterControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; this.Controls.Add(this.pnlCanvas); + this.Controls.Add(this.pnlStatusBar); this.Controls.Add(this.pnlControls); - this.Controls.Add(this.lblTitle); + this.Controls.Add(this.pnlHeader); this.Name = "GraphPlotterControl"; - this.Size = new System.Drawing.Size(800, 600); - this.pnlControls.ResumeLayout(false); - this.pnlGraphConfig.ResumeLayout(false); - this.pnlGraphConfig.PerformLayout(); - this.ResumeLayout(false); + this.Size = new Size(920, 660); + this.pnlControls.ResumeLayout(false); + this.pnlControls.PerformLayout(); + this.pnlStatusBar.ResumeLayout(false); + this.ResumeLayout(false); } - private System.Windows.Forms.Label lblTitle; - private System.Windows.Forms.Panel pnlControls; - private System.Windows.Forms.Panel pnlGraphConfig; - private System.Windows.Forms.Panel pnlCanvas; - - private System.Windows.Forms.Label lblEquation; - private System.Windows.Forms.TextBox txtEquation; - private System.Windows.Forms.Label lblMinX; - private System.Windows.Forms.TextBox txtMinX; - private System.Windows.Forms.Label lblMaxX; - private System.Windows.Forms.TextBox txtMaxX; - private System.Windows.Forms.Button btnPlot; + private Panel pnlHeader; + private Panel pnlControls; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnEx1; + private Button btnEx2; + private Button btnEx3; + private Button btnEx4; + private Label lblEquation; + private TextBox txtEquation; + private Label lblMinX; + private TextBox txtMinX; + private Label lblMaxX; + private TextBox txtMaxX; + private Button btnPlot; + private Button btnResetView; + private Button btnClearMarks; + private Panel pnlStatusBar; + private Label lblStatus; + private Panel pnlCanvas; } } diff --git a/MathApp/MathApp/Controls/GraphPlotterControl.cs b/MathApp/MathApp/Controls/GraphPlotterControl.cs index ad1d431..81662f5 100644 --- a/MathApp/MathApp/Controls/GraphPlotterControl.cs +++ b/MathApp/MathApp/Controls/GraphPlotterControl.cs @@ -1,145 +1,245 @@ using System; -using System.Drawing; -using System.Windows.Forms; using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Reflection; +using System.Windows.Forms; namespace MathApp.Controls { public partial class GraphPlotterControl : UserControl { - private List points = new List(); - private List markedPoints = new List(); // Points marked by user - - // Logical ranges - private float rangeMinX = -10; - private float rangeMaxX = 10; - private float rangeMinY = -10; - private float rangeMaxY = 10; - - private string currentEq = ""; + private List> segments = new List>(); + private List markedPoints = new List(); + + private float rangeMinX = -10f; + private float rangeMaxX = 10f; + private float rangeMinY = -6f; + private float rangeMaxY = 6f; + + private string currentEq = "sin(x)"; + private Function compiledFn = null; - // Mouse interaction state private bool isDragging = false; + private bool didMoveMouse = false; private Point lastMousePos; - + private Point? hoverMousePos = null; + public GraphPlotterControl() { InitializeComponent(); - btnPlot.Click += BtnPlot_Click; - - // Enable double buffering - SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); - UpdateStyles(); - // Attach mouse events to the canvas panel + // Enable DoubleBuffering on pnlCanvas to prevent flickering during pan/zoom + typeof(Panel).InvokeMember( + "DoubleBuffered", + BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, + null, + pnlCanvas, + new object[] { true }); + + btnPlot.Click += BtnPlot_Click; + btnResetView.Click += BtnResetView_Click; + btnClearMarks.Click += (s, e) => { markedPoints.Clear(); pnlCanvas.Invalidate(); }; + + btnEx1.Click += (s, e) => LoadPreset("sin(x) * x", -10f, 10f); + btnEx2.Click += (s, e) => LoadPreset("x^3 - 3*x", -3f, 3f); + btnEx3.Click += (s, e) => LoadPreset("exp(-x^2/4)*cos(2*x)", -6f, 6f); + btnEx4.Click += (s, e) => LoadPreset("1 / (x^2 - 1)", -5f, 5f); + + txtEquation.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPlot_Click(this, EventArgs.Empty); } }; + txtMinX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPlot_Click(this, EventArgs.Empty); } }; + txtMaxX.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; BtnPlot_Click(this, EventArgs.Empty); } }; + pnlCanvas.MouseDown += PnlCanvas_MouseDown; pnlCanvas.MouseMove += PnlCanvas_MouseMove; pnlCanvas.MouseUp += PnlCanvas_MouseUp; - pnlCanvas.MouseClick += PnlCanvas_MouseClick; - pnlCanvas.Resize += pnlCanvas_Resize; - pnlCanvas.Paint += pnlCanvas_Paint; + pnlCanvas.MouseLeave += (s, e) => { hoverMousePos = null; pnlCanvas.Invalidate(); }; + pnlCanvas.MouseWheel += PnlCanvas_MouseWheel; + + // Plot default function on startup + PlotNewEquation(true); + } + + private void LoadPreset(string eq, float minX, float maxX) + { + txtEquation.Text = eq; + txtMinX.Text = minX.ToString(CultureInfo.InvariantCulture); + txtMaxX.Text = maxX.ToString(CultureInfo.InvariantCulture); + PlotNewEquation(true); } private void BtnPlot_Click(object sender, EventArgs e) { - currentEq = txtEquation.Text; - markedPoints.Clear(); // Clear marks on new plot? Or keep them? Let's clear for fresh start. + PlotNewEquation(true); + } + + private void BtnResetView_Click(object sender, EventArgs e) + { + txtMinX.Text = "-10"; + txtMaxX.Text = "10"; + PlotNewEquation(true); + } + + private void PlotNewEquation(bool autoFitY) + { + currentEq = txtEquation.Text.Trim(); if (string.IsNullOrWhiteSpace(currentEq)) return; - rangeMinX = parse(txtMinX.Text, -10); - rangeMaxX = parse(txtMaxX.Text, 10); + rangeMinX = ParseFloat(txtMinX.Text, -10f); + rangeMaxX = ParseFloat(txtMaxX.Text, 10f); + if (rangeMinX >= rangeMaxX) + { + rangeMinX = -10f; + rangeMaxX = 10f; + } - GeneratePoints(); + try + { + compiledFn = NumericalMethods.CompileFunction(currentEq); + lblStatus.Text = $"✓ Çizildi: y = {currentEq} | Sol Tık + Sürükle: Kaydır | Tekerlek: Yakınlaştır | Tıkla: Nokta İşaretle"; + lblStatus.ForeColor = ThemeHelper.MutedText; + } + catch (Exception ex) + { + compiledFn = null; + segments.Clear(); + lblStatus.Text = "❌ Denklem Hatası: " + ex.Message; + lblStatus.ForeColor = ThemeHelper.DangerRed; + pnlCanvas.Invalidate(); + return; + } + + GeneratePoints(autoFitY); pnlCanvas.Invalidate(); } - private float parse(string s, float def) + private float ParseFloat(string s, float def) { - if (float.TryParse(s, out float v)) return v; + string norm = (s ?? "").Trim().Replace(',', '.'); + if (float.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out float v)) return v; return def; } - private void GeneratePoints() + private void GeneratePoints(bool autoFitY) { - points.Clear(); - float step = (rangeMaxX - rangeMinX) / 2000f; // Higher resolution + segments.Clear(); + if (compiledFn == null) return; + + int sampleCount = Math.Max(600, pnlCanvas.Width * 2); + float step = (rangeMaxX - rangeMinX) / sampleCount; + if (step <= 0) return; float tempMinY = float.MaxValue; float tempMaxY = float.MinValue; - for (float x = rangeMinX; x <= rangeMaxX; x += step) + List currentSegment = new List(); + float? prevY = null; + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try { - try + for (int i = 0; i <= sampleCount; i++) { - decimal val = NumericalMethods.Method_EvaluateFunction(currentEq, "x", (decimal)x); - float y = (float)val; + float x = rangeMinX + i * step; + try + { + decimal val = NumericalMethods.EvaluateCompiled(compiledFn, "x", (decimal)x); + float y = (float)val; - // Clamp excessively large values to avoid float overflow issues in GDI+ - if (y > 10000) y = 10000; - if (y < -10000) y = -10000; + if (float.IsNaN(y) || float.IsInfinity(y) || Math.Abs(y) > 1e6f) + { + if (currentSegment.Count > 1) segments.Add(currentSegment); + currentSegment = new List(); + prevY = null; + continue; + } - points.Add(new PointF(x, y)); + // Detect vertical asymptote jump (e.g. 1/x or tan(x)) + if (prevY.HasValue && Math.Abs(y - prevY.Value) > (rangeMaxY - rangeMinY) * 2.5f && (y * prevY.Value < 0)) + { + if (currentSegment.Count > 1) segments.Add(currentSegment); + currentSegment = new List(); + } - if (y < tempMinY) tempMinY = y; - if (y > tempMaxY) tempMaxY = y; - } - catch - { - // Ignore calculation errors (e.g. division by zero, out of domain) + currentSegment.Add(new PointF(x, y)); + prevY = y; + + if (Math.Abs(y) < 500f) + { + if (y < tempMinY) tempMinY = y; + if (y > tempMaxY) tempMaxY = y; + } + } + catch + { + if (currentSegment.Count > 1) segments.Add(currentSegment); + currentSegment = new List(); + prevY = null; + } } } - - // Auto-scale Y if it's the first plot or if we want to snap to range - // But if we are panning, we probably shouldn't auto-reset Y every time unless explicit. - // For now, let's set Y range based on data with some padding - if (tempMinY < tempMaxY) + finally { - float h = tempMaxY - tempMinY; - if (h == 0) h = 10; - rangeMinY = tempMinY - h * 0.1f; - rangeMaxY = tempMaxY + h * 0.1f; + Function.UseRadians = prevRad; } - else + + if (currentSegment.Count > 1) { - rangeMinY = -10; - rangeMaxY = 10; + segments.Add(currentSegment); + } + + if (autoFitY) + { + if (tempMinY < tempMaxY) + { + float h = tempMaxY - tempMinY; + if (h < 1e-3f) h = 4f; + rangeMinY = tempMinY - h * 0.18f; + rangeMaxY = tempMaxY + h * 0.18f; + } + else + { + rangeMinY = -10f; + rangeMaxY = 10f; + } } } - // --- Mouse Interaction --- - - protected override void OnMouseWheel(MouseEventArgs e) + private void PnlCanvas_MouseWheel(object sender, MouseEventArgs e) { - // Zoom Factor - float zoom = (e.Delta > 0) ? 0.9f : 1.1f; - - // Calculate center + float zoom = (e.Delta > 0) ? 0.85f : 1.18f; + float rangeW = rangeMaxX - rangeMinX; float rangeH = rangeMaxY - rangeMinY; - - float midX = (rangeMaxX + rangeMinX) / 2; - float midY = (rangeMaxY + rangeMinY) / 2; + if (rangeW < 1e-4f && zoom < 1f) return; + if (rangeW > 1e6f && zoom > 1f) return; + + float midX = (rangeMaxX + rangeMinX) / 2f; + float midY = (rangeMaxY + rangeMinY) / 2f; + + float halfW = (rangeW * zoom) / 2f; + float halfH = (rangeH * zoom) / 2f; - // Apply zoom centered - float halfW = (rangeW * zoom) / 2; - float halfH = (rangeH * zoom) / 2; - rangeMinX = midX - halfW; rangeMaxX = midX + halfW; rangeMinY = midY - halfH; rangeMaxY = midY + halfH; - - GeneratePoints(); + + txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture); + txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); + + GeneratePoints(false); pnlCanvas.Invalidate(); - - base.OnMouseWheel(e); // Let it bubble if needed } private void PnlCanvas_MouseDown(object sender, MouseEventArgs e) { + pnlCanvas.Focus(); if (e.Button == MouseButtons.Left) { isDragging = true; + didMoveMouse = false; lastMousePos = e.Location; Cursor = Cursors.SizeAll; } @@ -147,80 +247,88 @@ namespace MathApp.Controls private void PnlCanvas_MouseMove(object sender, MouseEventArgs e) { + hoverMousePos = e.Location; + if (isDragging) { - float dx = e.X - lastMousePos.X; - float dy = e.Y - lastMousePos.Y; + int dx = e.X - lastMousePos.X; + int dy = e.Y - lastMousePos.Y; + + if (Math.Abs(dx) > 2 || Math.Abs(dy) > 2) + { + didMoveMouse = true; + } float rangeW = rangeMaxX - rangeMinX; float rangeH = rangeMaxY - rangeMinY; - float w = pnlCanvas.Width; - float h = pnlCanvas.Height; + float w = Math.Max(1, pnlCanvas.Width); + float h = Math.Max(1, pnlCanvas.Height); - // Scale pixel delta to logical delta - // Note: dy is inverted because screen Y grows down, but math Y grows up float moveX = -dx * (rangeW / w); - float moveY = dy * (rangeH / h); + float moveY = dy * (rangeH / h); rangeMinX += moveX; rangeMaxX += moveX; rangeMinY += moveY; rangeMaxY += moveY; + txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture); + txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture); + lastMousePos = e.Location; - - // Re-generate points if we moved significantly to ensure we cover the new X range? - // Or just shift the view? - // If we shift X, we need new data points for the new X area. - // So we should re-generate. - GeneratePoints(); - - pnlCanvas.Invalidate(); + GeneratePoints(false); } + + pnlCanvas.Invalidate(); } private void PnlCanvas_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { + if (!didMoveMouse && compiledFn != null) + { + // Snap marked point onto the function curve at clicked X! + float w = Math.Max(1, pnlCanvas.Width); + float xPct = e.X / w; + float logX = rangeMinX + xPct * (rangeMaxX - rangeMinX); + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + decimal fx = NumericalMethods.EvaluateCompiled(compiledFn, "x", (decimal)logX); + markedPoints.Add(new PointF(logX, (float)fx)); + } + catch + { + float h = Math.Max(1, pnlCanvas.Height); + float yPct = (h - e.Y) / h; + float logY = rangeMinY + yPct * (rangeMaxY - rangeMinY); + markedPoints.Add(new PointF(logX, logY)); + } + finally + { + Function.UseRadians = prevRad; + } + } + isDragging = false; - Cursor = Cursors.Default; - } - } - - private void PnlCanvas_MouseClick(object sender, MouseEventArgs e) - { - // Right click or simple click (if not dragging) to mark point - if (!isDragging && e.Button == MouseButtons.Left) - { - // Unmap screen to logical - float w = pnlCanvas.Width; - float h = pnlCanvas.Height; - - float xPct = e.X / w; - float yPct = (h - e.Y) / h; // Invert Y - - float logX = rangeMinX + xPct * (rangeMaxX - rangeMinX); - float logY = rangeMinY + yPct * (rangeMaxY - rangeMinY); - - markedPoints.Add(new PointF(logX, logY)); + Cursor = Cursors.Cross; pnlCanvas.Invalidate(); } } - // --- Rendering --- - private void pnlCanvas_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; - float w = pnlCanvas.Width; - float h = pnlCanvas.Height; + float w = Math.Max(1, pnlCanvas.Width); + float h = Math.Max(1, pnlCanvas.Height); - // Map functions float MapX(float x) => (x - rangeMinX) / (rangeMaxX - rangeMinX) * w; float MapY(float y) => h - ((y - rangeMinY) / (rangeMaxY - rangeMinY) * h); @@ -228,7 +336,7 @@ namespace MathApp.Controls DrawGrid(g, w, h, MapX, MapY); // 2. Draw Axes - using (Pen axisPen = new Pen(Color.White, 2)) + using (Pen axisPen = new Pen(Color.FromArgb(148, 163, 184), 1.8f)) { float y0 = MapY(0); float x0 = MapX(0); @@ -237,98 +345,152 @@ namespace MathApp.Controls if (x0 >= 0 && x0 <= w) g.DrawLine(axisPen, x0, 0, x0, h); } - // 3. Draw Function - if (points.Count > 1) + // 3. Draw Function Curve Segments + if (segments.Count > 0) { - using (Pen graphPen = new Pen(Color.Cyan, 2)) + using (Pen glowPen = new Pen(Color.FromArgb(45, 56, 189, 248), 6f)) + using (Pen graphPen = new Pen(Color.FromArgb(56, 189, 248), 2.4f)) { - List screenPoints = new List(); - foreach (var p in points) + foreach (var seg in segments) { - screenPoints.Add(new PointF(MapX(p.X), MapY(p.Y))); - } + if (seg.Count < 2) continue; + List screenPoints = new List(seg.Count); + foreach (var p in seg) + { + float sx = MapX(p.X); + float sy = MapY(p.Y); + if (sy < -5000f) sy = -5000f; + if (sy > h + 5000f) sy = h + 5000f; + screenPoints.Add(new PointF(sx, sy)); + } - // Draw valid segments - // We shouldn't connect jumps between valid/invalid or huge leaps - // For simplicity, we draw lines. - try - { - // Clipping helps performance but GDI+ handles basic out-of-bounds well - // unless coordinates are floats.NaN or Infinity. - g.DrawLines(graphPen, screenPoints.ToArray()); - } - catch { } + try + { + PointF[] arr = screenPoints.ToArray(); + g.DrawLines(glowPen, arr); + g.DrawLines(graphPen, arr); + } + catch { } + } } } - // 4. Draw Marked Points - using(Brush markBrush = new SolidBrush(Color.Yellow)) - using(Pen markPen = new Pen(Color.Red, 2)) - using(Font markFont = new Font("Segoe UI", 9)) + // 4. Draw Live Hover Crosshair & f(x) Value + if (hoverMousePos.HasValue && !isDragging && compiledFn != null) { - foreach(var p in markedPoints) + float mx = hoverMousePos.Value.X; + float logX = rangeMinX + (mx / w) * (rangeMaxX - rangeMinX); + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try + { + decimal fxDec = NumericalMethods.EvaluateCompiled(compiledFn, "x", (decimal)logX); + float logY = (float)fxDec; + float sy = MapY(logY); + + using (Pen dashPen = new Pen(Color.FromArgb(90, 248, 250, 252), 1f)) + { + dashPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; + g.DrawLine(dashPen, mx, 0, mx, h); + if (sy >= 0 && sy <= h) + { + g.DrawLine(dashPen, 0, sy, w, sy); + using (Brush dotBrush = new SolidBrush(Color.FromArgb(56, 189, 248))) + { + g.FillEllipse(dotBrush, mx - 4, sy - 4, 8, 8); + } + } + } + + string coordInfo = $"x = {logX:F3} | f(x) = {logY:F4}"; + using (Font hudFont = new Font("Consolas", 9.5F, FontStyle.Bold)) + using (Brush hudBg = new SolidBrush(Color.FromArgb(210, 15, 23, 42))) + using (Brush hudFg = new SolidBrush(Color.FromArgb(186, 230, 253))) + { + SizeF sz = g.MeasureString(coordInfo, hudFont); + RectangleF rect = new RectangleF(w - sz.Width - 24, 12, sz.Width + 12, sz.Height + 8); + g.FillRectangle(hudBg, rect); + g.DrawString(coordInfo, hudFont, hudFg, rect.X + 6, rect.Y + 4); + } + } + catch { } + finally + { + Function.UseRadians = prevRad; + } + } + + // 5. Draw Marked Points + using (Brush markBrush = new SolidBrush(Color.FromArgb(250, 204, 21))) + using (Brush bgTag = new SolidBrush(Color.FromArgb(200, 15, 23, 42))) + using (Pen markPen = new Pen(Color.FromArgb(244, 63, 94), 2.2f)) + using (Font markFont = new Font("Consolas", 9F, FontStyle.Bold)) + { + foreach (var p in markedPoints) { float sx = MapX(p.X); float sy = MapY(p.Y); - - // Draw X mark - float r = 5; - g.DrawLine(markPen, sx - r, sy - r, sx + r, sy + r); - g.DrawLine(markPen, sx + r, sy - r, sx - r, sy + r); - - // Draw coordinates text + if (sx < -50 || sx > w + 50 || sy < -50 || sy > h + 50) continue; + + g.FillEllipse(markBrush, sx - 4, sy - 4, 8, 8); + g.DrawEllipse(markPen, sx - 6, sy - 6, 12, 12); + string coord = $"({p.X:F2}, {p.Y:F2})"; - g.DrawString(coord, markFont, markBrush, sx + 5, sy - 20); + SizeF sz = g.MeasureString(coord, markFont); + g.FillRectangle(bgTag, sx + 8, sy - 22, sz.Width + 4, sz.Height + 2); + g.DrawString(coord, markFont, markBrush, sx + 10, sy - 21); } } } private void DrawGrid(Graphics g, float w, float h, Func mapX, Func mapY) { - using (Pen gridPen = new Pen(Color.FromArgb(50, 50, 50), 1)) - using (Font font = new Font("Segoe UI", 8)) - using (Brush brush = new SolidBrush(Color.Gray)) + using (Pen gridPen = new Pen(Color.FromArgb(30, 41, 59), 1)) + using (Font font = new Font("Segoe UI", 8.5f)) + using (Brush brush = new SolidBrush(Color.FromArgb(148, 163, 184))) { - // Calculate roughly how many lines we want - int targetLinesW = 10; - int targetLinesH = 10; - float rangeW = rangeMaxX - rangeMinX; - float stepW = CalculateStep(rangeW, targetLinesW); + float stepW = CalculateStep(rangeW, 10); float rangeH = rangeMaxY - rangeMinY; - float stepH = CalculateStep(rangeH, targetLinesH); + float stepH = CalculateStep(rangeH, 8); - // Vertical Grid Lines - float startX = (float)Math.Floor(rangeMinX / stepW) * stepW; - for (float x = startX; x <= rangeMaxX; x += stepW) + if (stepW > 0) { - float sx = mapX(x); - g.DrawLine(gridPen, sx, 0, sx, h); - g.DrawString(x.ToString("0.##"), font, brush, sx + 2, h - 20); + float startX = (float)Math.Floor(rangeMinX / stepW) * stepW; + for (float x = startX; x <= rangeMaxX; x += stepW) + { + float sx = mapX(x); + g.DrawLine(gridPen, sx, 0, sx, h); + g.DrawString(x.ToString("0.##", CultureInfo.InvariantCulture), font, brush, sx + 3, h - 20); + } } - // Horizontal Grid Lines - float startY = (float)Math.Floor(rangeMinY / stepH) * stepH; - for (float y = startY; y <= rangeMaxY; y += stepH) + if (stepH > 0) { - float sy = mapY(y); - g.DrawLine(gridPen, 0, sy, w, sy); - g.DrawString(y.ToString("0.##"), font, brush, 5, sy - 15); + float startY = (float)Math.Floor(rangeMinY / stepH) * stepH; + for (float y = startY; y <= rangeMaxY; y += stepH) + { + float sy = mapY(y); + g.DrawLine(gridPen, 0, sy, w, sy); + g.DrawString(y.ToString("0.##", CultureInfo.InvariantCulture), font, brush, 6, sy - 16); + } } } } - + private float CalculateStep(float range, int targetSteps) { - float rawStep = range / targetSteps; - float mag = (float)Math.Pow(10, Math.Floor(Math.Log10(rawStep))); - float normStep = rawStep / mag; - - if (normStep < 1.5) return 1 * mag; - if (normStep < 3.5) return 2 * mag; - if (normStep < 7.5) return 5 * mag; - return 10 * mag; + if (range <= 0 || float.IsNaN(range) || float.IsInfinity(range)) return 1f; + float rawStep = range / targetSteps; + float mag = (float)Math.Pow(10, Math.Floor(Math.Log10(rawStep))); + float normStep = rawStep / mag; + + if (normStep < 1.5f) return 1f * mag; + if (normStep < 3.5f) return 2f * mag; + if (normStep < 7.5f) return 5f * mag; + return 10f * mag; } private void pnlCanvas_Resize(object sender, EventArgs e) diff --git a/MathApp/MathApp/Controls/MatrixCalculatorControl.Designer.cs b/MathApp/MathApp/Controls/MatrixCalculatorControl.Designer.cs new file mode 100644 index 0000000..78a300e --- /dev/null +++ b/MathApp/MathApp/Controls/MatrixCalculatorControl.Designer.cs @@ -0,0 +1,434 @@ +using System.Drawing; +using System.Windows.Forms; + +namespace MathApp.Controls +{ + partial class MatrixCalculatorControl + { + private System.ComponentModel.IContainer components = null; + private Panel pnlLeft; + private Label lblTitle; + private Label lblDesc; + + // Matrix A section + private Label lblHeaderA; + private NumericUpDown numRowsA; + private NumericUpDown numColsA; + private Button btnResizeA; + private Button btnRandomA; + private Button btnIdentityA; + private Button btnZeroA; + private Panel pnlGridA; + + // Matrix B section + private Label lblHeaderB; + private NumericUpDown numRowsB; + private NumericUpDown numColsB; + private Button btnResizeB; + private Button btnRandomB; + private Button btnIdentityB; + private Button btnZeroB; + private Button btnCopyAToB; + private Panel pnlGridB; + + // Scalar & Presets + private Label lblScalar; + private TextBox txtScalar; + private Button btnExSPD; + private Button btnExGeneral; + + // Single Matrix A Operations + private Label lblOpsA; + private Button btnAllProps; + private Button btnLU; + private Button btnQR; + private Button btnCholesky; + private Button btnSVD; + private Button btnEigen; + private Button btnInverse; + + // Dual Matrix A & B Operations + private Label lblOpsAB; + private Button btnAddAB; + private Button btnSubAB; + private Button btnMulAB; + private Button btnElemMul; + private Button btnElemDiv; + private Button btnScalarMul; + private Button btnSolveAXB; + private Button btnSolveTrans; + + // Right side results & actions + private Panel pnlRight; + private Panel pnlResultToolbar; + private Button btnAnsToA; + private Button btnCopyMatrix; + private Label lblResultTitle; + private RichTextBox txtResult; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) components.Dispose(); + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.pnlLeft = new Panel(); + this.lblTitle = new Label(); + this.lblDesc = new Label(); + + this.lblHeaderA = new Label(); + this.numRowsA = new NumericUpDown(); + this.numColsA = new NumericUpDown(); + this.btnResizeA = new Button(); + this.btnRandomA = new Button(); + this.btnIdentityA = new Button(); + this.btnZeroA = new Button(); + this.pnlGridA = new Panel(); + + this.lblHeaderB = new Label(); + this.numRowsB = new NumericUpDown(); + this.numColsB = new NumericUpDown(); + this.btnResizeB = new Button(); + this.btnRandomB = new Button(); + this.btnIdentityB = new Button(); + this.btnZeroB = new Button(); + this.btnCopyAToB = new Button(); + this.pnlGridB = new Panel(); + + this.lblScalar = new Label(); + this.txtScalar = new TextBox(); + this.btnExSPD = new Button(); + this.btnExGeneral = new Button(); + + this.lblOpsA = new Label(); + this.btnAllProps = new Button(); + this.btnLU = new Button(); + this.btnQR = new Button(); + this.btnCholesky = new Button(); + this.btnSVD = new Button(); + this.btnEigen = new Button(); + this.btnInverse = new Button(); + + this.lblOpsAB = new Label(); + this.btnAddAB = new Button(); + this.btnSubAB = new Button(); + this.btnMulAB = new Button(); + this.btnElemMul = new Button(); + this.btnElemDiv = new Button(); + this.btnScalarMul = new Button(); + this.btnSolveAXB = new Button(); + this.btnSolveTrans = new Button(); + + this.pnlRight = new Panel(); + this.pnlResultToolbar = new Panel(); + this.lblResultTitle = new Label(); + this.btnAnsToA = new Button(); + this.btnCopyMatrix = new Button(); + this.txtResult = new RichTextBox(); + + this.SuspendLayout(); + + this.BackColor = Color.FromArgb(24, 25, 32); + this.Dock = DockStyle.Fill; + this.Padding = new Padding(12); + + this.pnlLeft.Dock = DockStyle.Left; + this.pnlLeft.Width = 445; + this.pnlLeft.BackColor = Color.FromArgb(30, 32, 42); + this.pnlLeft.Padding = new Padding(12); + this.pnlLeft.AutoScroll = true; + + this.lblTitle.Text = "Matris Cebiri & Ayrıştırma Stüdyosu"; + this.lblTitle.Font = new Font("Segoe UI", 12.5F, FontStyle.Bold); + this.lblTitle.ForeColor = Color.White; + this.lblTitle.Location = new Point(12, 10); + this.lblTitle.AutoSize = true; + + this.lblDesc.Text = "A ve B matrisleri üzerinde cebir, AX=B sistemleri ve LU/QR/SVD ayrıştırmaları."; + this.lblDesc.Font = new Font("Segoe UI", 8.5F); + this.lblDesc.ForeColor = Color.FromArgb(165, 175, 195); + this.lblDesc.Location = new Point(12, 34); + this.lblDesc.Size = new Size(415, 18); + + // --- MATRIX A --- + this.lblHeaderA.Text = "A Matrisi (m × n):"; + this.lblHeaderA.Font = new Font("Segoe UI", 9F, FontStyle.Bold); + this.lblHeaderA.ForeColor = Color.FromArgb(110, 190, 255); + this.lblHeaderA.Location = new Point(12, 56); + this.lblHeaderA.AutoSize = true; + + ((System.ComponentModel.ISupportInitialize)(this.numRowsA)).BeginInit(); + this.numRowsA.Location = new Point(130, 54); + this.numRowsA.Minimum = 1; + this.numRowsA.Maximum = 6; + this.numRowsA.Value = 3; + this.numRowsA.Size = new Size(38, 24); + this.numRowsA.BackColor = Color.FromArgb(40, 43, 56); + this.numRowsA.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numRowsA)).EndInit(); + + ((System.ComponentModel.ISupportInitialize)(this.numColsA)).BeginInit(); + this.numColsA.Location = new Point(172, 54); + this.numColsA.Minimum = 1; + this.numColsA.Maximum = 6; + this.numColsA.Value = 3; + this.numColsA.Size = new Size(38, 24); + this.numColsA.BackColor = Color.FromArgb(40, 43, 56); + this.numColsA.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numColsA)).EndInit(); + + StyleSmallBtn(btnResizeA, "Boyutla", new Point(214, 53), new Size(54, 25)); + StyleSmallBtn(btnRandomA, "Rastgele", new Point(272, 53), new Size(58, 25)); + StyleSmallBtn(btnIdentityA, "I", new Point(334, 53), new Size(34, 25)); + StyleSmallBtn(btnZeroA, "0", new Point(372, 53), new Size(34, 25)); + + this.pnlGridA.Location = new Point(12, 82); + this.pnlGridA.Size = new Size(410, 118); + this.pnlGridA.BackColor = Color.FromArgb(24, 26, 34); + this.pnlGridA.AutoScroll = true; + + // --- MATRIX B --- + this.lblHeaderB.Text = "B Matrisi (Sağ Taraf):"; + this.lblHeaderB.Font = new Font("Segoe UI", 9F, FontStyle.Bold); + this.lblHeaderB.ForeColor = Color.FromArgb(140, 225, 175); + this.lblHeaderB.Location = new Point(12, 206); + this.lblHeaderB.AutoSize = true; + + ((System.ComponentModel.ISupportInitialize)(this.numRowsB)).BeginInit(); + this.numRowsB.Location = new Point(130, 204); + this.numRowsB.Minimum = 1; + this.numRowsB.Maximum = 6; + this.numRowsB.Value = 3; + this.numRowsB.Size = new Size(38, 24); + this.numRowsB.BackColor = Color.FromArgb(40, 43, 56); + this.numRowsB.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numRowsB)).EndInit(); + + ((System.ComponentModel.ISupportInitialize)(this.numColsB)).BeginInit(); + this.numColsB.Location = new Point(172, 204); + this.numColsB.Minimum = 1; + this.numColsB.Maximum = 6; + this.numColsB.Value = 3; + this.numColsB.Size = new Size(38, 24); + this.numColsB.BackColor = Color.FromArgb(40, 43, 56); + this.numColsB.ForeColor = Color.White; + ((System.ComponentModel.ISupportInitialize)(this.numColsB)).EndInit(); + + StyleSmallBtn(btnResizeB, "Boyutla", new Point(214, 203), new Size(54, 25)); + StyleSmallBtn(btnRandomB, "Rastgele", new Point(272, 203), new Size(58, 25)); + StyleSmallBtn(btnIdentityB, "I", new Point(334, 203), new Size(34, 25)); + StyleSmallBtn(btnZeroB, "0", new Point(372, 203), new Size(34, 25)); + + this.pnlGridB.Location = new Point(12, 232); + this.pnlGridB.Size = new Size(410, 118); + this.pnlGridB.BackColor = Color.FromArgb(24, 26, 34); + this.pnlGridB.AutoScroll = true; + + // --- SCALAR & PRESETS --- + this.lblScalar.Text = "Skaler k:"; + this.lblScalar.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + this.lblScalar.ForeColor = Color.FromArgb(190, 200, 215); + this.lblScalar.Location = new Point(12, 358); + this.lblScalar.AutoSize = true; + + this.txtScalar.Location = new Point(68, 355); + this.txtScalar.Size = new Size(46, 24); + this.txtScalar.BackColor = Color.FromArgb(40, 43, 56); + this.txtScalar.ForeColor = Color.White; + this.txtScalar.BorderStyle = BorderStyle.FixedSingle; + this.txtScalar.Text = "2.5"; + + StyleSmallBtn(btnCopyAToB, "A→B Kopyala", new Point(118, 354), new Size(88, 25)); + StyleSmallBtn(btnExSPD, "Örnek SPD", new Point(210, 354), new Size(96, 25)); + StyleSmallBtn(btnExGeneral, "Örnek Genel", new Point(310, 354), new Size(98, 25)); + + // --- A OPERATIONS --- + this.lblOpsA.Text = "A Matrisi Analiz & Ayrıştırma (LU, QR, SVD, Cholesky, Özdeğer):"; + this.lblOpsA.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + this.lblOpsA.ForeColor = Color.FromArgb(180, 195, 220); + this.lblOpsA.Location = new Point(12, 384); + this.lblOpsA.AutoSize = true; + + this.btnAllProps.Text = "📊 A Matrisi Tam Analiz (Det, Rank, Norm2, Kondisyon, Tersi)"; + this.btnAllProps.Location = new Point(12, 403); + this.btnAllProps.Size = new Size(410, 30); + this.btnAllProps.BackColor = Color.FromArgb(46, 125, 225); + this.btnAllProps.ForeColor = Color.White; + this.btnAllProps.FlatStyle = FlatStyle.Flat; + this.btnAllProps.FlatAppearance.BorderSize = 0; + this.btnAllProps.Font = new Font("Segoe UI", 9F, FontStyle.Bold); + this.btnAllProps.Cursor = Cursors.Hand; + + StyleOpBtn(btnLU, "LU Ayrıştırma", new Point(12, 437), new Size(132, 27)); + StyleOpBtn(btnQR, "QR & Householder", new Point(150, 437), new Size(134, 27)); + StyleOpBtn(btnCholesky, "Cholesky (LLᵀ)", new Point(290, 437), new Size(132, 27)); + StyleOpBtn(btnSVD, "SVD (U·Σ·Vᵀ)", new Point(12, 467), new Size(132, 27)); + StyleOpBtn(btnEigen, "Özdeğer (λ, V)", new Point(150, 467), new Size(134, 27)); + StyleOpBtn(btnInverse, "Ters & Transpoz", new Point(290, 467), new Size(132, 27)); + + // --- A & B BINARY OPERATIONS --- + this.lblOpsAB.Text = "İki Matrisli Cebir (A ve B) & Matris Denklem Çözücü:"; + this.lblOpsAB.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + this.lblOpsAB.ForeColor = Color.FromArgb(140, 225, 175); + this.lblOpsAB.Location = new Point(12, 498); + this.lblOpsAB.AutoSize = true; + + StyleBinaryBtn(btnAddAB, "A + B", new Point(12, 517), new Size(98, 27)); + StyleBinaryBtn(btnSubAB, "A - B", new Point(116, 517), new Size(98, 27)); + StyleBinaryBtn(btnMulAB, "A × B (Çarpım)", new Point(220, 517), new Size(98, 27)); + StyleBinaryBtn(btnScalarMul, "k · A", new Point(324, 517), new Size(98, 27)); + + StyleBinaryBtn(btnElemMul, "A .* B (Hadamard)", new Point(12, 547), new Size(132, 27)); + StyleBinaryBtn(btnElemDiv, "A ./ B (Eleman Böl)", new Point(150, 547), new Size(134, 27)); + StyleBinaryBtn(btnSolveAXB, "Çöz: A·X = B", new Point(290, 547), new Size(132, 27)); + + this.btnSolveTrans.Text = "Transpoz Denklem Çözücü: Aᵀ · Xᵀ = Bᵀ (SolveTranspose)"; + this.btnSolveTrans.Location = new Point(12, 577); + this.btnSolveTrans.Size = new Size(410, 27); + this.btnSolveTrans.BackColor = Color.FromArgb(38, 85, 78); + this.btnSolveTrans.ForeColor = Color.White; + this.btnSolveTrans.FlatStyle = FlatStyle.Flat; + this.btnSolveTrans.FlatAppearance.BorderSize = 0; + this.btnSolveTrans.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + this.btnSolveTrans.Cursor = Cursors.Hand; + + this.pnlLeft.Controls.Add(this.lblTitle); + this.pnlLeft.Controls.Add(this.lblDesc); + this.pnlLeft.Controls.Add(this.lblHeaderA); + this.pnlLeft.Controls.Add(this.numRowsA); + this.pnlLeft.Controls.Add(this.numColsA); + this.pnlLeft.Controls.Add(this.btnResizeA); + this.pnlLeft.Controls.Add(this.btnRandomA); + this.pnlLeft.Controls.Add(this.btnIdentityA); + this.pnlLeft.Controls.Add(this.btnZeroA); + this.pnlLeft.Controls.Add(this.pnlGridA); + + this.pnlLeft.Controls.Add(this.lblHeaderB); + this.pnlLeft.Controls.Add(this.numRowsB); + this.pnlLeft.Controls.Add(this.numColsB); + this.pnlLeft.Controls.Add(this.btnResizeB); + this.pnlLeft.Controls.Add(this.btnRandomB); + this.pnlLeft.Controls.Add(this.btnIdentityB); + this.pnlLeft.Controls.Add(this.btnZeroB); + this.pnlLeft.Controls.Add(this.pnlGridB); + + this.pnlLeft.Controls.Add(this.lblScalar); + this.pnlLeft.Controls.Add(this.txtScalar); + this.pnlLeft.Controls.Add(this.btnCopyAToB); + this.pnlLeft.Controls.Add(this.btnExSPD); + this.pnlLeft.Controls.Add(this.btnExGeneral); + + this.pnlLeft.Controls.Add(this.lblOpsA); + this.pnlLeft.Controls.Add(this.btnAllProps); + this.pnlLeft.Controls.Add(this.btnLU); + this.pnlLeft.Controls.Add(this.btnQR); + this.pnlLeft.Controls.Add(this.btnCholesky); + this.pnlLeft.Controls.Add(this.btnSVD); + this.pnlLeft.Controls.Add(this.btnEigen); + this.pnlLeft.Controls.Add(this.btnInverse); + + this.pnlLeft.Controls.Add(this.lblOpsAB); + this.pnlLeft.Controls.Add(this.btnAddAB); + this.pnlLeft.Controls.Add(this.btnSubAB); + this.pnlLeft.Controls.Add(this.btnMulAB); + this.pnlLeft.Controls.Add(this.btnScalarMul); + this.pnlLeft.Controls.Add(this.btnElemMul); + this.pnlLeft.Controls.Add(this.btnElemDiv); + this.pnlLeft.Controls.Add(this.btnSolveAXB); + this.pnlLeft.Controls.Add(this.btnSolveTrans); + + // Right Pane with Toolbar + this.pnlRight.Dock = DockStyle.Fill; + this.pnlRight.Padding = new Padding(12, 0, 0, 0); + + this.pnlResultToolbar.Dock = DockStyle.Top; + this.pnlResultToolbar.Height = 36; + this.pnlResultToolbar.BackColor = Color.FromArgb(24, 25, 32); + + this.lblResultTitle.Text = "📊 Matris Analiz & İşlem Çıktısı:"; + this.lblResultTitle.Dock = DockStyle.Left; + this.lblResultTitle.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblResultTitle.ForeColor = ThemeHelper.LightText; + this.lblResultTitle.TextAlign = ContentAlignment.MiddleLeft; + + this.btnAnsToA.Text = "📥 Sonucu Matris A'ya Aktar (Ans→A)"; + this.btnAnsToA.Dock = DockStyle.Right; + this.btnAnsToA.Width = 220; + this.btnAnsToA.FlatStyle = FlatStyle.Flat; + this.btnAnsToA.BackColor = Color.FromArgb(37, 99, 235); + this.btnAnsToA.ForeColor = Color.White; + this.btnAnsToA.Font = new Font("Segoe UI Semibold", 8.5F, FontStyle.Bold); + this.btnAnsToA.FlatAppearance.BorderSize = 0; + this.btnAnsToA.Cursor = Cursors.Hand; + + this.btnCopyMatrix.Text = "📋 Kopyala"; + this.btnCopyMatrix.Dock = DockStyle.Right; + this.btnCopyMatrix.Width = 85; + this.btnCopyMatrix.FlatStyle = FlatStyle.Flat; + this.btnCopyMatrix.BackColor = ThemeHelper.ButtonSecondary; + this.btnCopyMatrix.ForeColor = Color.White; + this.btnCopyMatrix.Font = new Font("Segoe UI", 8.5F); + this.btnCopyMatrix.FlatAppearance.BorderSize = 0; + this.btnCopyMatrix.Cursor = Cursors.Hand; + + this.pnlResultToolbar.Controls.Add(this.lblResultTitle); + this.pnlResultToolbar.Controls.Add(this.btnCopyMatrix); + this.pnlResultToolbar.Controls.Add(this.btnAnsToA); + + this.txtResult.Dock = DockStyle.Fill; + this.txtResult.BackColor = Color.FromArgb(18, 19, 25); + this.txtResult.ForeColor = Color.FromArgb(225, 232, 245); + this.txtResult.Font = new Font("Consolas", 10F); + this.txtResult.BorderStyle = BorderStyle.None; + this.txtResult.ReadOnly = true; + + this.pnlRight.Controls.Add(this.txtResult); + this.pnlRight.Controls.Add(this.pnlResultToolbar); + + this.Controls.Add(this.pnlRight); + this.Controls.Add(this.pnlLeft); + this.ResumeLayout(false); + } + + private void StyleSmallBtn(Button b, string text, Point loc, Size sz) + { + b.Text = text; + b.Location = loc; + b.Size = sz; + b.BackColor = Color.FromArgb(45, 50, 68); + b.ForeColor = Color.FromArgb(215, 225, 245); + b.FlatStyle = FlatStyle.Flat; + b.FlatAppearance.BorderSize = 0; + b.Font = new Font("Segoe UI", 8F); + b.Cursor = Cursors.Hand; + } + + private void StyleOpBtn(Button b, string text, Point loc, Size sz) + { + b.Text = text; + b.Location = loc; + b.Size = sz; + b.BackColor = Color.FromArgb(52, 60, 84); + b.ForeColor = Color.White; + b.FlatStyle = FlatStyle.Flat; + b.FlatAppearance.BorderSize = 0; + b.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + b.Cursor = Cursors.Hand; + } + + private void StyleBinaryBtn(Button b, string text, Point loc, Size sz) + { + b.Text = text; + b.Location = loc; + b.Size = sz; + b.BackColor = Color.FromArgb(40, 95, 76); + b.ForeColor = Color.White; + b.FlatStyle = FlatStyle.Flat; + b.FlatAppearance.BorderSize = 0; + b.Font = new Font("Segoe UI", 8.5F, FontStyle.Bold); + b.Cursor = Cursors.Hand; + } + } +} diff --git a/MathApp/MathApp/Controls/MatrixCalculatorControl.cs b/MathApp/MathApp/Controls/MatrixCalculatorControl.cs new file mode 100644 index 0000000..39df583 --- /dev/null +++ b/MathApp/MathApp/Controls/MatrixCalculatorControl.cs @@ -0,0 +1,490 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.Text; +using System.Windows.Forms; +using DotNetMatrix; + +namespace MathApp.Controls +{ + public partial class MatrixCalculatorControl : UserControl + { + private TextBox[,] gridCellsA; + private TextBox[,] gridCellsB; + private int rowsA = 3, colsA = 3; + private int rowsB = 3, colsB = 3; + private GeneralMatrix lastResultMatrix = null; + + public MatrixCalculatorControl() + { + InitializeComponent(); + + btnResizeA.Click += (s, e) => BuildGridA((int)numRowsA.Value, (int)numColsA.Value); + btnRandomA.Click += (s, e) => FillRandom(gridCellsA, rowsA, colsA); + btnIdentityA.Click += (s, e) => FillIdentity(gridCellsA, rowsA, colsA); + btnZeroA.Click += (s, e) => FillZero(gridCellsA, rowsA, colsA); + + btnResizeB.Click += (s, e) => BuildGridB((int)numRowsB.Value, (int)numColsB.Value); + btnRandomB.Click += (s, e) => FillRandom(gridCellsB, rowsB, colsB); + btnIdentityB.Click += (s, e) => FillIdentity(gridCellsB, rowsB, colsB); + btnZeroB.Click += (s, e) => FillZero(gridCellsB, rowsB, colsB); + btnCopyAToB.Click += BtnCopyAToB_Click; + + btnAnsToA.Click += BtnAnsToA_Click; + btnCopyMatrix.Click += (s, e) => { + if (!string.IsNullOrEmpty(txtResult.Text)) + { + Clipboard.SetText(txtResult.Text); + MessageBox.Show("Matris çıktısı panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + btnExSPD.Click += (s, e) => LoadPresetMatrices( + new decimal[,] { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }, + new decimal[,] { { 1, 2, 0 }, { 2, 5, 1 }, { 0, 1, 3 } }); + + btnExGeneral.Click += (s, e) => LoadPresetMatrices( + new decimal[,] { { 2, 1, 1 }, { 4, -6, 0 }, { -2, 7, 2 } }, + new decimal[,] { { 1, 0, 2 }, { -1, 3, 1 }, { 2, 1, 4 } }); + + // Single Matrix A Decompositions & Properties + btnAllProps.Click += (s, e) => RunUnaryOperation("ALL"); + btnLU.Click += (s, e) => RunUnaryOperation("LU"); + btnQR.Click += (s, e) => RunUnaryOperation("QR"); + btnCholesky.Click += (s, e) => RunUnaryOperation("CHOLESKY"); + btnSVD.Click += (s, e) => RunUnaryOperation("SVD"); + btnEigen.Click += (s, e) => RunUnaryOperation("EIGEN"); + btnInverse.Click += (s, e) => RunUnaryOperation("INVERSE"); + + // Dual Matrix (A & B) Arithmetic & Solvers + btnAddAB.Click += (s, e) => RunBinaryOperation("ADD"); + btnSubAB.Click += (s, e) => RunBinaryOperation("SUB"); + btnMulAB.Click += (s, e) => RunBinaryOperation("MUL"); + btnElemMul.Click += (s, e) => RunBinaryOperation("ELEM_MUL"); + btnElemDiv.Click += (s, e) => RunBinaryOperation("ELEM_DIV"); + btnScalarMul.Click += (s, e) => RunBinaryOperation("SCALAR"); + btnSolveAXB.Click += (s, e) => RunBinaryOperation("SOLVE"); + btnSolveTrans.Click += (s, e) => RunBinaryOperation("SOLVE_TRANS"); + + LoadPresetMatrices( + new decimal[,] { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }, + new decimal[,] { { 1, 2, 0 }, { 2, 5, 1 }, { 0, 1, 3 } }, + autoRun: false); + } + + private void LoadPresetMatrices(decimal[,] dataA, decimal[,] dataB, bool autoRun = true) + { + numRowsA.Value = dataA.GetLength(0); + numColsA.Value = dataA.GetLength(1); + BuildGridA(dataA.GetLength(0), dataA.GetLength(1)); + for (int i = 0; i < rowsA; i++) + for (int j = 0; j < colsA; j++) + gridCellsA[i, j].Text = dataA[i, j].ToString(CultureInfo.InvariantCulture); + + numRowsB.Value = dataB.GetLength(0); + numColsB.Value = dataB.GetLength(1); + BuildGridB(dataB.GetLength(0), dataB.GetLength(1)); + for (int i = 0; i < rowsB; i++) + for (int j = 0; j < colsB; j++) + gridCellsB[i, j].Text = dataB[i, j].ToString(CultureInfo.InvariantCulture); + + if (autoRun) RunUnaryOperation("ALL"); + } + + private void BtnCopyAToB_Click(object sender, EventArgs e) + { + numRowsB.Value = rowsA; + numColsB.Value = colsA; + BuildGridB(rowsA, colsA); + for (int i = 0; i < rowsA; i++) + for (int j = 0; j < colsA; j++) + gridCellsB[i, j].Text = gridCellsA[i, j].Text; + } + + private void BuildGridA(int r, int c) + { + rowsA = r; colsA = c; + gridCellsA = BuildGridInternal(pnlGridA, r, c); + } + + private void BuildGridB(int r, int c) + { + rowsB = r; colsB = c; + gridCellsB = BuildGridInternal(pnlGridB, r, c); + } + + private TextBox[,] BuildGridInternal(Panel container, int rows, int cols) + { + container.SuspendLayout(); + container.Controls.Clear(); + TextBox[,] cells = new TextBox[rows, cols]; + int cellW = 58; + int cellH = 26; + int gap = 4; + + for (int i = 0; i < rows; i++) + { + for (int j = 0; j < cols; j++) + { + TextBox tb = new TextBox + { + Location = new Point(6 + j * (cellW + gap), 6 + i * (cellH + gap)), + Size = new Size(cellW, cellH), + BackColor = ThemeHelper.CardBackground, + ForeColor = Color.White, + BorderStyle = BorderStyle.FixedSingle, + Font = new Font("Consolas", 10F, FontStyle.Bold), + TextAlign = HorizontalAlignment.Center, + Text = (i == j) ? "1" : "0" + }; + cells[i, j] = tb; + container.Controls.Add(tb); + } + } + container.ResumeLayout(); + return cells; + } + + private void FillRandom(TextBox[,] cells, int r, int c) + { + decimal[][] rand = Matrix.GenerateRandomMatrix(r, c, -9, 9); + for (int i = 0; i < r; i++) + for (int j = 0; j < c; j++) + cells[i, j].Text = Math.Round(rand[i][j], 0).ToString(CultureInfo.InvariantCulture); + } + + private void FillZero(TextBox[,] cells, int r, int c) + { + for (int i = 0; i < r; i++) + for (int j = 0; j < c; j++) + cells[i, j].Text = "0"; + } + + private void BtnAnsToA_Click(object sender, EventArgs e) + { + if (lastResultMatrix == null) + { + MessageBox.Show("Aktarılacak matris sonucu bulunamadı. Önce bir işlem yapınız.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + + int r = Math.Min(6, lastResultMatrix.RowDimension); + int c = Math.Min(6, lastResultMatrix.ColumnDimension); + + numRowsA.Value = r; + numColsA.Value = c; + BuildGridA(r, c); + + for (int i = 0; i < r; i++) + for (int j = 0; j < c; j++) + gridCellsA[i, j].Text = Math.Round(lastResultMatrix.GetElement(i, j), 6).ToString(CultureInfo.InvariantCulture); + + MessageBox.Show($"Sonuç matrisi ({r}x{c}) başarıyla Matris A'ya aktarıldı!", "Başarılı", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + private void FillIdentity(TextBox[,] cells, int r, int c) + { + for (int i = 0; i < r; i++) + for (int j = 0; j < c; j++) + cells[i, j].Text = (i == j) ? "1" : "0"; + } + + private GeneralMatrix ReadMatrix(TextBox[,] cells, int r, int c, string name) + { + decimal[][] arr = new decimal[r][]; + for (int i = 0; i < r; i++) + { + arr[i] = new decimal[c]; + for (int j = 0; j < c; j++) + { + string raw = cells[i, j].Text.Trim().Replace(',', '.'); + if (!decimal.TryParse(raw, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) + { + throw new ArgumentException($"{name} matrisinin ({i + 1}, {j + 1}) hücresinde geçersiz sayı: '{cells[i, j].Text}'"); + } + arr[i][j] = val; + } + } + return new GeneralMatrix(arr); + } + + private string FormatMatrix(GeneralMatrix m) + { + StringBuilder sb = new StringBuilder(); + decimal[][] a = m.Array; + for (int i = 0; i < m.RowDimension; i++) + { + sb.Append(" [ "); + for (int j = 0; j < m.ColumnDimension; j++) + { + decimal v = Math.Round(a[i][j], 5); + if (DecimalMath.Abs(v) < 0.000001m) v = 0m; + sb.Append($"{v.ToString("0.#####", CultureInfo.InvariantCulture),11}"); + if (j < m.ColumnDimension - 1) sb.Append(" "); + } + sb.AppendLine(" ]"); + } + return sb.ToString(); + } + + private void RunBinaryOperation(string op) + { + try + { + GeneralMatrix A = ReadMatrix(gridCellsA, rowsA, colsA, "A"); + StringBuilder sb = new StringBuilder(); + + if (op == "SCALAR") + { + string sRaw = txtScalar.Text.Trim().Replace(',', '.'); + if (!decimal.TryParse(sRaw, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal 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; + } + + GeneralMatrix B = ReadMatrix(gridCellsB, rowsB, colsB, "B"); + + 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)); + } + + txtResult.Text = sb.ToString(); + } + catch (Exception ex) + { + txtResult.Text = "❌ İşlem Hatası: " + ex.Message; + } + } + + private void RunUnaryOperation(string op) + { + try + { + GeneralMatrix A = ReadMatrix(gridCellsA, rowsA, colsA, "A"); + StringBuilder sb = new StringBuilder(); + + if (op == "ALL") + { + 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)}"); + + try + { + 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 { } + + 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") + { + 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)); + } + } + + txtResult.Text = sb.ToString(); + } + catch (Exception ex) + { + txtResult.Text = "❌ Hesaplama Hatası: " + ex.Message; + } + } + } +} diff --git a/MathApp/MathApp/Controls/MultivariableTaylorControl.Designer.cs b/MathApp/MathApp/Controls/MultivariableTaylorControl.Designer.cs index ca92646..06786a5 100644 --- a/MathApp/MathApp/Controls/MultivariableTaylorControl.Designer.cs +++ b/MathApp/MathApp/Controls/MultivariableTaylorControl.Designer.cs @@ -1,3 +1,6 @@ +using System; +using System.Drawing; +using System.Windows.Forms; namespace MathApp.Controls { @@ -16,189 +19,174 @@ namespace MathApp.Controls private void InitializeComponent() { - this.lblTitle = new System.Windows.Forms.Label(); - this.lblEquation = new System.Windows.Forms.Label(); - this.txtEquation = new System.Windows.Forms.TextBox(); - this.lblOrder = new System.Windows.Forms.Label(); - this.numOrder = new System.Windows.Forms.NumericUpDown(); - this.grpVariables = new System.Windows.Forms.GroupBox(); - this.pnlVariables = new System.Windows.Forms.FlowLayoutPanel(); - this.btnAddVar = new System.Windows.Forms.Button(); - this.btnCalculate = new System.Windows.Forms.Button(); - this.lblResult = new System.Windows.Forms.Label(); - this.txtResult = new System.Windows.Forms.TextBox(); + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Çok Değişkenli Taylor Serisi (Multivariable Taylor)", + "f(x, y, ...) fonksiyonları için tüm kısmi ve çapraz (mixed partial) türevleri içeren tam çok değişkenli Taylor açılımı."); + + this.pnlContent = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnEx1 = ThemeHelper.CreateExampleChip("Örnek 1: sin(x)*cos(y)"); + this.btnEx2 = ThemeHelper.CreateExampleChip("Örnek 2: exp(x + y)"); + this.btnEx3 = ThemeHelper.CreateExampleChip("Örnek 3: x²y + y³ (1, 2)"); + + this.lblEquation = new Label(); + this.txtEquation = new TextBox(); + this.lblOrder = new Label(); + this.numOrder = new NumericUpDown(); + this.grpVariables = new GroupBox(); + this.pnlVariables = new FlowLayoutPanel(); + this.btnAddVar = ThemeHelper.CreateActionButton("+ Değişken Ekle", 150, 30, false); + this.btnCalculate = ThemeHelper.CreateActionButton("📐 Seriyi Hesapla", 190, 38, true); + this.lblResult = new Label(); + this.txtResult = new TextBox(); + ((System.ComponentModel.ISupportInitialize)(this.numOrder)).BeginInit(); this.grpVariables.SuspendLayout(); + this.pnlContent.SuspendLayout(); this.SuspendLayout(); - // - // lblTitle - // - this.lblTitle.AutoSize = true; - this.lblTitle.Font = new System.Drawing.Font("Segoe UI Light", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.lblTitle.ForeColor = System.Drawing.Color.White; - this.lblTitle.Location = new System.Drawing.Point(20, 20); - this.lblTitle.Name = "lblTitle"; - this.lblTitle.Size = new System.Drawing.Size(280, 32); - this.lblTitle.TabIndex = 0; - this.lblTitle.Text = "Multivariable Taylor Series"; - // - // lblEquation - // + + this.pnlContent.Dock = DockStyle.Fill; + this.pnlContent.BackColor = ThemeHelper.DarkBackground; + this.pnlContent.Padding = new Padding(24, 16, 24, 24); + + this.lblPresets.Text = "Hızlı Örnekler:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 6, 10, 0); + + this.pnlPresets.Location = new Point(24, 14); + this.pnlPresets.Size = new Size(800, 36); + this.pnlPresets.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnEx1); + this.pnlPresets.Controls.Add(this.btnEx2); + this.pnlPresets.Controls.Add(this.btnEx3); + + int y = 60; + this.lblEquation.AutoSize = true; - this.lblEquation.ForeColor = System.Drawing.Color.White; - this.lblEquation.Location = new System.Drawing.Point(23, 70); - this.lblEquation.Name = "lblEquation"; - this.lblEquation.Size = new System.Drawing.Size(89, 15); - this.lblEquation.TabIndex = 1; - this.lblEquation.Text = "Function f(...) ="; - // - // txtEquation - // - this.txtEquation.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtEquation.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtEquation.ForeColor = System.Drawing.Color.White; - this.txtEquation.Location = new System.Drawing.Point(118, 68); - this.txtEquation.Name = "txtEquation"; - this.txtEquation.Size = new System.Drawing.Size(300, 23); - this.txtEquation.TabIndex = 2; + this.lblEquation.ForeColor = ThemeHelper.LightText; + this.lblEquation.Font = new Font("Segoe UI", 10F); + this.lblEquation.Location = new Point(24, y + 3); + this.lblEquation.Text = "Fonksiyon f(x,y,...):"; + + this.txtEquation.BackColor = ThemeHelper.CardBackground; + this.txtEquation.BorderStyle = BorderStyle.FixedSingle; + this.txtEquation.ForeColor = Color.White; + this.txtEquation.Font = new Font("Consolas", 11F); + this.txtEquation.Location = new Point(165, y); + this.txtEquation.Size = new Size(290, 27); this.txtEquation.Text = "sin(x)*cos(y)"; - // - // lblOrder - // + this.lblOrder.AutoSize = true; - this.lblOrder.ForeColor = System.Drawing.Color.White; - this.lblOrder.Location = new System.Drawing.Point(440, 70); - this.lblOrder.Name = "lblOrder"; - this.lblOrder.Size = new System.Drawing.Size(74, 15); - this.lblOrder.TabIndex = 3; - this.lblOrder.Text = "Series Order:"; - // - // numOrder - // - this.numOrder.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.numOrder.ForeColor = System.Drawing.Color.White; - this.numOrder.Location = new System.Drawing.Point(520, 68); - this.numOrder.Maximum = new decimal(new int[] { - 10, - 0, - 0, - 0}); - this.numOrder.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 0}); - this.numOrder.Name = "numOrder"; - this.numOrder.Size = new System.Drawing.Size(60, 23); - this.numOrder.TabIndex = 4; - this.numOrder.Value = new decimal(new int[] { - 2, - 0, - 0, - 0}); - // - // grpVariables - // + this.lblOrder.ForeColor = ThemeHelper.LightText; + this.lblOrder.Font = new Font("Segoe UI", 10F); + this.lblOrder.Location = new Point(475, y + 3); + this.lblOrder.Text = "Derece (n):"; + + this.numOrder.BackColor = ThemeHelper.CardBackground; + this.numOrder.ForeColor = Color.White; + this.numOrder.BorderStyle = BorderStyle.FixedSingle; + this.numOrder.Font = new Font("Consolas", 11F); + this.numOrder.Location = new Point(560, y); + this.numOrder.Maximum = 5; + this.numOrder.Minimum = 1; + this.numOrder.Size = new Size(65, 27); + this.numOrder.Value = 3; + + this.btnCalculate.Location = new Point(645, y - 5); + y += 46; + this.grpVariables.Controls.Add(this.pnlVariables); this.grpVariables.Controls.Add(this.btnAddVar); - this.grpVariables.ForeColor = System.Drawing.Color.White; - this.grpVariables.Location = new System.Drawing.Point(23, 110); - this.grpVariables.Name = "grpVariables"; - this.grpVariables.Size = new System.Drawing.Size(557, 200); - this.grpVariables.TabIndex = 5; + this.grpVariables.ForeColor = ThemeHelper.LightText; + this.grpVariables.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.grpVariables.Location = new Point(24, y); + this.grpVariables.Size = new Size(820, 195); + this.grpVariables.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.grpVariables.TabStop = false; - this.grpVariables.Text = "Variables & Expansion Points"; - // - // pnlVariables - // + this.grpVariables.Text = "Değişkenler ve Açılım Merkez Noktaları"; + this.pnlVariables.AutoScroll = true; - this.pnlVariables.Location = new System.Drawing.Point(10, 25); - this.pnlVariables.Name = "pnlVariables"; - this.pnlVariables.Size = new System.Drawing.Size(530, 130); - this.pnlVariables.TabIndex = 1; - // - // btnAddVar - // - this.btnAddVar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); - this.btnAddVar.FlatAppearance.BorderSize = 0; - this.btnAddVar.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnAddVar.Location = new System.Drawing.Point(10, 165); - this.btnAddVar.Name = "btnAddVar"; - this.btnAddVar.Size = new System.Drawing.Size(120, 25); - this.btnAddVar.TabIndex = 0; - this.btnAddVar.Text = "+ Add Variable"; - this.btnAddVar.UseVisualStyleBackColor = false; - // - // btnCalculate - // - this.btnCalculate.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(120)))), ((int)(((byte)(215))))); - this.btnCalculate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnCalculate.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.btnCalculate.ForeColor = System.Drawing.Color.White; - this.btnCalculate.Location = new System.Drawing.Point(23, 330); - this.btnCalculate.Name = "btnCalculate"; - this.btnCalculate.Size = new System.Drawing.Size(150, 40); - this.btnCalculate.TabIndex = 6; - this.btnCalculate.Text = "Calculate Expansion"; - this.btnCalculate.UseVisualStyleBackColor = false; - // - // lblResult - // + this.pnlVariables.FlowDirection = FlowDirection.TopDown; + this.pnlVariables.WrapContents = false; + this.pnlVariables.Location = new Point(12, 26); + this.pnlVariables.Size = new Size(796, 122); + this.pnlVariables.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlVariables.BackColor = Color.FromArgb(11, 17, 32); + this.pnlVariables.Padding = new Padding(6); + + this.btnAddVar.Location = new Point(12, 155); + y += 208; + this.lblResult.AutoSize = true; - this.lblResult.ForeColor = System.Drawing.Color.White; - this.lblResult.Location = new System.Drawing.Point(23, 390); - this.lblResult.Name = "lblResult"; - this.lblResult.Size = new System.Drawing.Size(42, 15); - this.lblResult.TabIndex = 7; - this.lblResult.Text = "Result:"; - // - // txtResult - // - this.txtResult.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30))))); - this.txtResult.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtResult.Font = new System.Drawing.Font("Consolas", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.txtResult.ForeColor = System.Drawing.Color.Cyan; - this.txtResult.Location = new System.Drawing.Point(23, 410); + this.lblResult.ForeColor = ThemeHelper.LightText; + this.lblResult.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold); + this.lblResult.Location = new Point(24, y); + this.lblResult.Text = "📊 Çok Değişkenli Taylor Polinomu:"; + + this.btnCopyMultiTaylor = ThemeHelper.CreateCopyButton("📋 Kopyala"); + this.btnCopyMultiTaylor.Location = new Point(750, y - 4); + this.btnCopyMultiTaylor.Anchor = AnchorStyles.Top | AnchorStyles.Right; + + y += 26; + + this.txtResult.BackColor = ThemeHelper.CardBackground; + this.txtResult.BorderStyle = BorderStyle.FixedSingle; + this.txtResult.Font = new Font("Consolas", 10.5F); + this.txtResult.ForeColor = Color.FromArgb(186, 230, 253); + this.txtResult.Location = new Point(24, y); this.txtResult.Multiline = true; - this.txtResult.Name = "txtResult"; this.txtResult.ReadOnly = true; - this.txtResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.txtResult.Size = new System.Drawing.Size(557, 150); - this.txtResult.TabIndex = 8; - // - // MultivariableTaylorControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); - this.Controls.Add(this.txtResult); - this.Controls.Add(this.lblResult); - this.Controls.Add(this.btnCalculate); - this.Controls.Add(this.grpVariables); - this.Controls.Add(this.numOrder); - this.Controls.Add(this.lblOrder); - this.Controls.Add(this.txtEquation); - this.Controls.Add(this.lblEquation); - this.Controls.Add(this.lblTitle); + this.txtResult.ScrollBars = ScrollBars.Vertical; + this.txtResult.Size = new Size(820, 215); + this.txtResult.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + + this.pnlContent.Controls.Add(this.btnCopyMultiTaylor); + this.pnlContent.Controls.Add(this.pnlPresets); + this.pnlContent.Controls.Add(this.txtResult); + this.pnlContent.Controls.Add(this.lblResult); + this.pnlContent.Controls.Add(this.btnCalculate); + this.pnlContent.Controls.Add(this.grpVariables); + this.pnlContent.Controls.Add(this.numOrder); + this.pnlContent.Controls.Add(this.lblOrder); + this.pnlContent.Controls.Add(this.txtEquation); + this.pnlContent.Controls.Add(this.lblEquation); + + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.pnlContent); + this.Controls.Add(this.pnlHeader); this.Name = "MultivariableTaylorControl"; - this.Size = new System.Drawing.Size(600, 600); + this.Size = new Size(880, 660); + ((System.ComponentModel.ISupportInitialize)(this.numOrder)).EndInit(); this.grpVariables.ResumeLayout(false); + this.pnlContent.ResumeLayout(false); + this.pnlContent.PerformLayout(); this.ResumeLayout(false); - this.PerformLayout(); - } - private System.Windows.Forms.Label lblTitle; - private System.Windows.Forms.Label lblEquation; - private System.Windows.Forms.TextBox txtEquation; - private System.Windows.Forms.Label lblOrder; - private System.Windows.Forms.NumericUpDown numOrder; - private System.Windows.Forms.GroupBox grpVariables; - private System.Windows.Forms.FlowLayoutPanel pnlVariables; - private System.Windows.Forms.Button btnAddVar; - private System.Windows.Forms.Button btnCalculate; - private System.Windows.Forms.Label lblResult; - private System.Windows.Forms.TextBox txtResult; + private Panel pnlHeader; + private Panel pnlContent; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnEx1; + private Button btnEx2; + private Button btnEx3; + private Label lblEquation; + private TextBox txtEquation; + private Label lblOrder; + private NumericUpDown numOrder; + private GroupBox grpVariables; + private FlowLayoutPanel pnlVariables; + private Button btnAddVar; + private Button btnCalculate; + private Label lblResult; + private Button btnCopyMultiTaylor; + private TextBox txtResult; } } diff --git a/MathApp/MathApp/Controls/MultivariableTaylorControl.cs b/MathApp/MathApp/Controls/MultivariableTaylorControl.cs index c8f41cd..e20ac61 100644 --- a/MathApp/MathApp/Controls/MultivariableTaylorControl.cs +++ b/MathApp/MathApp/Controls/MultivariableTaylorControl.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.Windows.Forms; using System.Globalization; +using System.Linq; +using System.Windows.Forms; namespace MathApp.Controls { @@ -15,26 +16,60 @@ namespace MathApp.Controls InitializeComponent(); btnAddVar.Click += BtnAddVar_Click; btnCalculate.Click += BtnCalculate_Click; - - // Add initial variables inputs (x and y default) + + btnEx1.Click += (s, e) => LoadPreset("sin(x)*cos(y)", 3, new[] { ("x", "0"), ("y", "0") }); + btnEx2.Click += (s, e) => LoadPreset("exp(x + y)", 2, new[] { ("x", "0"), ("y", "0") }); + btnEx3.Click += (s, e) => LoadPreset("x^2*y + y^3", 3, new[] { ("x", "1"), ("y", "2") }); + + btnCopyMultiTaylor.Click += (s, e) => { + if (!string.IsNullOrEmpty(txtResult.Text)) + { + Clipboard.SetText(txtResult.Text); + MessageBox.Show("Çok değişkenli Taylor serisi panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + txtEquation.KeyDown += (s, e) => { + if (e.KeyCode == Keys.Enter) + { + e.SuppressKeyPress = true; + BtnCalculate_Click(this, EventArgs.Empty); + } + }; + AddVariableRow("x", "0"); AddVariableRow("y", "0"); } + private void LoadPreset(string eq, int order, (string v, string val)[] vars) + { + txtEquation.Text = eq; + numOrder.Value = order; + pnlVariables.Controls.Clear(); + variableRows.Clear(); + foreach (var item in vars) + { + AddVariableRow(item.v, item.val); + } + BtnCalculate_Click(this, EventArgs.Empty); + } + private void BtnAddVar_Click(object sender, EventArgs e) { - AddVariableRow("", "0"); + string[] names = { "x", "y", "z", "w", "u", "v" }; + string suggested = variableRows.Count < names.Length ? names[variableRows.Count] : "v" + (variableRows.Count + 1); + AddVariableRow(suggested, "0"); } private void AddVariableRow(string varName, string val) { VariableInputRow row = new VariableInputRow(varName, val); - row.OnRemove += (s, e) => + row.OnRemove += (s, e) => { pnlVariables.Controls.Remove(row.Panel); variableRows.Remove(row); }; - + pnlVariables.Controls.Add(row.Panel); variableRows.Add(row); } @@ -43,51 +78,70 @@ namespace MathApp.Controls { try { - string eq = txtEquation.Text; + string eq = txtEquation.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) + { + txtResult.Text = "Lütfen bir çok değişkenli fonksiyon giriniz."; + return; + } + int degree = (int)numOrder.Value; Dictionary points = new Dictionary(); - foreach(var row in variableRows) + foreach (var row in variableRows) { string v = row.Variable; - if(string.IsNullOrWhiteSpace(v)) continue; - - decimal p = 0; - if(!decimal.TryParse(row.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out p)) + if (string.IsNullOrWhiteSpace(v)) continue; + + string valNorm = row.Value.Replace(',', '.'); + if (!decimal.TryParse(valNorm, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal p)) { - txtResult.Text = "Invalid number format for variable: " + v; + txtResult.Text = $"❌ '{v}' değişkeni için geçerli bir sayı giriniz."; return; } - - if(points.ContainsKey(v)) + + if (points.ContainsKey(v)) { - txtResult.Text = "Duplicate variable: " + v; + txtResult.Text = $"❌ '{v}' değişkeni birden fazla kez eklenmiş."; return; } points.Add(v, p); } - if(points.Count == 0) + if (points.Count == 0) { - txtResult.Text = "Please add at least one variable."; + txtResult.Text = "⚠️ Lütfen en az bir değişken ekleyiniz."; return; } - string result = NumericalMethods.MethodMultiVar_TaylorSeries(eq, degree, points); - - // Formatting clean up - result = result.Replace("+ -", "- ").Replace("+-", "- ").Replace("*", " * "); - - txtResult.Text = result; + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + string result; + try + { + result = 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}")); + + txtResult.Text = + $"=== Çok Değişkenli Taylor Açılımı ({degree}. Derece, Çapraz Kısmi Türevler Dahil) ===" + Environment.NewLine + + $"Fonksiyon : f({varsList}) = {eq}" + Environment.NewLine + + $"Merkez : ({centerList})" + Environment.NewLine + Environment.NewLine + + $"T_{degree}({varsList}) ≈ {result}"; } catch (Exception ex) { - txtResult.Text = "Error: " + ex.Message; + txtResult.Text = "❌ Hata: " + ex.Message; } } } - // Helper class for dynamic rows public class VariableInputRow { public Panel Panel { get; private set; } @@ -100,16 +154,66 @@ namespace MathApp.Controls public VariableInputRow(string varName, string val) { - Panel = new Panel(); - Panel.Size = new Size(500, 30); - - Label lblVar = new Label { Text = "Var:", Location = new Point(0, 5), AutoSize = true, ForeColor = Color.White }; - TxtVariable = new TextBox { Text = varName, Location = new Point(40, 2), Size = new Size(100, 23), BackColor = Color.FromArgb(40,40,40), ForeColor = Color.White, BorderStyle = BorderStyle.FixedSingle }; - - Label lblVal = new Label { Text = "Point:", Location = new Point(160, 5), AutoSize = true, ForeColor = Color.White }; - TxtValue = new TextBox { Text = val, Location = new Point(210, 2), Size = new Size(100, 23), BackColor = Color.FromArgb(40,40,40), ForeColor = Color.White, BorderStyle = BorderStyle.FixedSingle }; - - Button btnRemove = new Button { Text = "X", Location = new Point(330, 2), Size = new Size(30, 23), BackColor = Color.Red, ForeColor = Color.White, FlatStyle = FlatStyle.Flat }; + Panel = new Panel + { + Size = new Size(520, 34), + BackColor = ThemeHelper.CardBackground, + Margin = new Padding(0, 0, 0, 5) + }; + + Label lblVar = new Label + { + Text = "Değişken:", + Location = new Point(10, 8), + AutoSize = true, + ForeColor = ThemeHelper.LightText, + Font = new Font("Segoe UI", 9.5F) + }; + + TxtVariable = new TextBox + { + Text = varName, + Location = new Point(85, 5), + Size = new Size(80, 25), + BackColor = ThemeHelper.InputBackground, + ForeColor = Color.FromArgb(56, 189, 248), + BorderStyle = BorderStyle.FixedSingle, + Font = new Font("Consolas", 10.5F, FontStyle.Bold), + TextAlign = HorizontalAlignment.Center + }; + + Label lblVal = new Label + { + Text = "Merkez Noktası:", + Location = new Point(185, 8), + AutoSize = true, + ForeColor = ThemeHelper.LightText, + Font = new Font("Segoe UI", 9.5F) + }; + + TxtValue = new TextBox + { + Text = val, + Location = new Point(295, 5), + Size = new Size(100, 25), + BackColor = ThemeHelper.InputBackground, + ForeColor = Color.White, + BorderStyle = BorderStyle.FixedSingle, + Font = new Font("Consolas", 10.5F), + TextAlign = HorizontalAlignment.Center + }; + + Button btnRemove = new Button + { + Text = "✕ Sil", + Location = new Point(415, 4), + Size = new Size(65, 26), + BackColor = Color.FromArgb(153, 27, 27), + ForeColor = Color.White, + FlatStyle = FlatStyle.Flat, + Font = new Font("Segoe UI Semibold", 8.5F, FontStyle.Bold), + Cursor = Cursors.Hand + }; btnRemove.FlatAppearance.BorderSize = 0; btnRemove.Click += (s, e) => OnRemove?.Invoke(this, EventArgs.Empty); diff --git a/MathApp/MathApp/Controls/RootFinderControl.Designer.cs b/MathApp/MathApp/Controls/RootFinderControl.Designer.cs index ef4f577..36f1a7c 100644 --- a/MathApp/MathApp/Controls/RootFinderControl.Designer.cs +++ b/MathApp/MathApp/Controls/RootFinderControl.Designer.cs @@ -1,3 +1,5 @@ +using System.Drawing; +using System.Windows.Forms; namespace MathApp.Controls { @@ -7,216 +9,279 @@ namespace MathApp.Controls protected override void Dispose(bool disposing) { - if (disposing && (components != null)) - { - components.Dispose(); - } + if (disposing && (components != null)) components.Dispose(); base.Dispose(disposing); } private void InitializeComponent() { - this.lblTitle = new System.Windows.Forms.Label(); - this.pnlContent = new System.Windows.Forms.Panel(); - - this.lblMethod = new System.Windows.Forms.Label(); - this.cmbMethod = new System.Windows.Forms.ComboBox(); - this.lblEquation = new System.Windows.Forms.Label(); - this.txtEquation = new System.Windows.Forms.TextBox(); - this.lblVariable = new System.Windows.Forms.Label(); - this.txtVariable = new System.Windows.Forms.TextBox(); - this.lblInitialPoint = new System.Windows.Forms.Label(); - this.txtInitialPoint = new System.Windows.Forms.TextBox(); - this.lblMinX = new System.Windows.Forms.Label(); - this.txtMinX = new System.Windows.Forms.TextBox(); - this.lblMaxX = new System.Windows.Forms.Label(); - this.txtMaxX = new System.Windows.Forms.TextBox(); - this.lblIterations = new System.Windows.Forms.Label(); - this.txtIterations = new System.Windows.Forms.TextBox(); - this.btnFindRoot = new System.Windows.Forms.Button(); - this.lblResult = new System.Windows.Forms.Label(); - this.txtResult = new System.Windows.Forms.TextBox(); + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Denklem Kökü Bulucu (Root Finder)", + "Newton-Raphson, Bisection, Secant ve Regula Falsi algoritmaları ile yüksek hassasiyetli sayısal kök bulma."); + + this.pnlContent = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnEx1 = ThemeHelper.CreateExampleChip("Örnek 1: x³ - x - 2 = 0"); + this.btnEx2 = ThemeHelper.CreateExampleChip("Örnek 2: cos(x) - x = 0"); + this.btnEx3 = ThemeHelper.CreateExampleChip("Örnek 3: e^x - 3x = 0"); + + this.pnlInputsCard = new Panel(); + this.lblMethod = new Label(); + this.cmbMethod = new ComboBox(); + this.lblMethodDesc = new Label(); + + this.lblEquation = new Label(); + this.txtEquation = new TextBox(); + this.lblVariable = new Label(); + this.txtVariable = new TextBox(); + + this.lblInitialPoint = new Label(); + this.txtInitialPoint = new TextBox(); + this.lblMinX = new Label(); + this.txtMinX = new TextBox(); + this.lblMaxX = new Label(); + this.txtMaxX = new TextBox(); + + this.lblIterations = new Label(); + this.txtIterations = new TextBox(); + this.btnFindRoot = ThemeHelper.CreateActionButton("🔍 Kökü Hesapla", 180, 36, true); + + // Hero Summary Card + this.pnlSummary = new Panel(); + this.lblRootSummaryTitle = new Label(); + this.lblRootValue = new Label(); + this.lblRootDetails = new Label(); + this.btnCopyResult = ThemeHelper.CreateCopyButton("📋 Kopyala"); + + // Results details + this.lblLogTitle = new Label(); + this.txtResult = new TextBox(); this.pnlContent.SuspendLayout(); + this.pnlInputsCard.SuspendLayout(); + this.pnlSummary.SuspendLayout(); this.SuspendLayout(); - // - // lblTitle - // - this.lblTitle.Dock = System.Windows.Forms.DockStyle.Top; - this.lblTitle.Font = new System.Drawing.Font("Segoe UI Light", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.lblTitle.ForeColor = System.Drawing.Color.White; - this.lblTitle.Location = new System.Drawing.Point(0, 0); - this.lblTitle.Name = "lblTitle"; - this.lblTitle.Size = new System.Drawing.Size(800, 60); - this.lblTitle.TabIndex = 0; - this.lblTitle.Text = "Equation Root Finder"; - this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.pnlContent.Dock = DockStyle.Fill; + this.pnlContent.BackColor = ThemeHelper.DarkBackground; + this.pnlContent.Padding = new Padding(24, 14, 24, 20); + this.pnlContent.AutoScroll = true; - // - // pnlContent - // - this.pnlContent.Controls.Add(this.txtResult); - this.pnlContent.Controls.Add(this.lblResult); - this.pnlContent.Controls.Add(this.btnFindRoot); - this.pnlContent.Controls.Add(this.txtIterations); - this.pnlContent.Controls.Add(this.lblIterations); - this.pnlContent.Controls.Add(this.txtMaxX); - this.pnlContent.Controls.Add(this.lblMaxX); - this.pnlContent.Controls.Add(this.txtMinX); - this.pnlContent.Controls.Add(this.lblMinX); - this.pnlContent.Controls.Add(this.txtInitialPoint); - this.pnlContent.Controls.Add(this.lblInitialPoint); - this.pnlContent.Controls.Add(this.txtVariable); - this.pnlContent.Controls.Add(this.lblVariable); - this.pnlContent.Controls.Add(this.txtEquation); - this.pnlContent.Controls.Add(this.lblEquation); - this.pnlContent.Controls.Add(this.cmbMethod); - this.pnlContent.Controls.Add(this.lblMethod); - this.pnlContent.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlContent.Location = new System.Drawing.Point(0, 60); - this.pnlContent.Name = "pnlContent"; - this.pnlContent.Size = new System.Drawing.Size(800, 540); - this.pnlContent.TabIndex = 1; + // Presets row + this.lblPresets.Text = "⚡ Hızlı Örnekler:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); - // Simple layout similar to previous, but styling updated in logic or here - int yObject = 20; + this.pnlPresets.Location = new Point(24, 12); + this.pnlPresets.Size = new Size(860, 34); + this.pnlPresets.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnEx1); + this.pnlPresets.Controls.Add(this.btnEx2); + this.pnlPresets.Controls.Add(this.btnEx3); - // Helper to style labels - void StyleLabel(System.Windows.Forms.Label l) { + // Inputs Card + this.pnlInputsCard.Location = new Point(24, 52); + this.pnlInputsCard.Size = new Size(860, 166); + this.pnlInputsCard.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlInputsCard.BackColor = ThemeHelper.CardBackground; + this.pnlInputsCard.Padding = new Padding(16, 12, 16, 12); + + void StyleLabel(Label l, string text, Point loc) + { + l.Text = text; + l.Location = loc; l.AutoSize = true; - l.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - l.ForeColor = System.Drawing.Color.White; + l.Font = new Font("Segoe UI", 9.5F, FontStyle.Regular); + l.ForeColor = ThemeHelper.LightText; } - StyleLabel(this.lblMethod); - this.lblMethod.Location = new System.Drawing.Point(20, yObject); - this.lblMethod.Text = "Method:"; - + void StyleInput(TextBox t, string def, Point loc, Size sz) + { + t.Location = loc; + t.Size = sz; + t.BackColor = Color.FromArgb(15, 23, 42); + t.BorderStyle = BorderStyle.FixedSingle; + t.ForeColor = Color.White; + t.Font = new Font("Consolas", 10.5F); + t.Text = def; + } + + // Method Selector + StyleLabel(this.lblMethod, "Nümerik Yöntem:", new Point(14, 15)); this.cmbMethod.FormattingEnabled = true; - this.cmbMethod.Items.AddRange(new object[] { "Newton-Raphson", "Bisection", "Secant", "Regula Falsi" }); - this.cmbMethod.Location = new System.Drawing.Point(150, yObject); - this.cmbMethod.Name = "cmbMethod"; - this.cmbMethod.Size = new System.Drawing.Size(200, 25); - this.cmbMethod.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - yObject += 50; + this.cmbMethod.Items.AddRange(new object[] { + "Newton-Raphson (Türev Tabanlı — En Hızlı Yakınsama)", + "Bisection (İkiye Bölme — Garantili Aralık Yakınsaması)", + "Secant (Kiriş Yöntemi — Türev Gerektirmeyen Yaklaşım)", + "Regula Falsi (Doğrusal İnterpolasyon ile Kök Bulma)" + }); + this.cmbMethod.Location = new Point(140, 12); + this.cmbMethod.Size = new Size(440, 26); + this.cmbMethod.Font = new Font("Segoe UI", 9.5F); + this.cmbMethod.BackColor = Color.FromArgb(15, 23, 42); + this.cmbMethod.ForeColor = Color.White; + this.cmbMethod.DropDownStyle = ComboBoxStyle.DropDownList; - StyleLabel(this.lblEquation); - this.lblEquation.Location = new System.Drawing.Point(20, yObject); - this.lblEquation.Text = "Equation:"; - this.txtEquation.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtEquation.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtEquation.ForeColor = System.Drawing.Color.White; - this.txtEquation.Location = new System.Drawing.Point(150, yObject); - this.txtEquation.Size = new System.Drawing.Size(400, 25); - yObject += 50; + // Method description hint + this.lblMethodDesc.Location = new Point(140, 42); + this.lblMethodDesc.Size = new Size(700, 18); + this.lblMethodDesc.Font = new Font("Segoe UI", 8.5F); + this.lblMethodDesc.ForeColor = Color.FromArgb(125, 211, 252); + this.lblMethodDesc.Text = "💡 Fonksiyonun analitik türevi ile teğet çizerek hızlıca köke ulaşır. Tek bir başlangıç (x₀) yeterlidir."; - StyleLabel(this.lblVariable); - this.lblVariable.Location = new System.Drawing.Point(20, yObject); - this.lblVariable.Text = "Variable (e.g. x):"; - this.txtVariable.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtVariable.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtVariable.ForeColor = System.Drawing.Color.White; - this.txtVariable.Location = new System.Drawing.Point(150, yObject); - this.txtVariable.Size = new System.Drawing.Size(100, 25); - yObject += 50; + // Equation & Variable + StyleLabel(this.lblEquation, "Denklem f(x) = 0:", new Point(14, 69)); + StyleInput(this.txtEquation, "x^3 - x - 2", new Point(140, 66), new Size(340, 26)); - StyleLabel(this.lblInitialPoint); - this.lblInitialPoint.Location = new System.Drawing.Point(20, yObject); - this.lblInitialPoint.Text = "Initial Point:"; - this.txtInitialPoint.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtInitialPoint.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtInitialPoint.ForeColor = System.Drawing.Color.White; - this.txtInitialPoint.Location = new System.Drawing.Point(150, yObject); - this.txtInitialPoint.Size = new System.Drawing.Size(100, 25); - - StyleLabel(this.lblMinX); - this.lblMinX.Location = new System.Drawing.Point(20, yObject); - this.lblMinX.Text = "Min X:"; - this.txtMinX.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtMinX.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtMinX.ForeColor = System.Drawing.Color.White; - this.txtMinX.Location = new System.Drawing.Point(150, yObject); - this.txtMinX.Size = new System.Drawing.Size(100, 25); - - StyleLabel(this.lblMaxX); - this.lblMaxX.Location = new System.Drawing.Point(280, yObject); - this.lblMaxX.Text = "Max X:"; - this.txtMaxX.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtMaxX.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtMaxX.ForeColor = System.Drawing.Color.White; - this.txtMaxX.Location = new System.Drawing.Point(340, yObject); - this.txtMaxX.Size = new System.Drawing.Size(100, 25); - yObject += 50; + StyleLabel(this.lblVariable, "Değişken:", new Point(495, 69)); + StyleInput(this.txtVariable, "x", new Point(565, 66), new Size(60, 26)); - StyleLabel(this.lblIterations); - this.lblIterations.Location = new System.Drawing.Point(20, yObject); - this.lblIterations.Text = "Iterations:"; - this.txtIterations.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtIterations.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtIterations.ForeColor = System.Drawing.Color.White; - this.txtIterations.Location = new System.Drawing.Point(150, yObject); - this.txtIterations.Size = new System.Drawing.Size(100, 25); - this.txtIterations.Text = "100"; - yObject += 60; + // Numerical points + StyleLabel(this.lblInitialPoint, "Başlangıç (x₀):", new Point(14, 102)); + StyleInput(this.txtInitialPoint, "1.5", new Point(140, 99), new Size(110, 26)); - this.btnFindRoot.Location = new System.Drawing.Point(150, yObject); - this.btnFindRoot.Name = "btnFindRoot"; - this.btnFindRoot.Size = new System.Drawing.Size(150, 40); - this.btnFindRoot.Text = "Find Root"; - this.btnFindRoot.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnFindRoot.BackColor = System.Drawing.Color.FromArgb(0, 120, 215); - this.btnFindRoot.ForeColor = System.Drawing.Color.White; - this.btnFindRoot.Font = new System.Drawing.Font("Segoe UI Semibold", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); - this.btnFindRoot.FlatAppearance.BorderSize = 0; - yObject += 60; + StyleLabel(this.lblMinX, "Alt Sınır (a):", new Point(14, 102)); + StyleInput(this.txtMinX, "1", new Point(140, 99), new Size(110, 26)); - StyleLabel(this.lblResult); - this.lblResult.Location = new System.Drawing.Point(20, yObject); - this.lblResult.Text = "Result:"; - this.txtResult.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30))))); - this.txtResult.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtResult.ForeColor = System.Drawing.Color.White; - this.txtResult.Location = new System.Drawing.Point(150, yObject); - this.txtResult.Size = new System.Drawing.Size(600, 150); + StyleLabel(this.lblMaxX, "Üst Sınır (b):", new Point(270, 102)); + StyleInput(this.txtMaxX, "2", new Point(360, 99), new Size(110, 26)); + + StyleLabel(this.lblIterations, "Maks. İterasyon:", new Point(495, 102)); + StyleInput(this.txtIterations, "50", new Point(610, 99), new Size(65, 26)); + + // Solve Button + this.btnFindRoot.Location = new Point(140, 131); + this.btnFindRoot.Size = new Size(220, 32); + + this.pnlInputsCard.Controls.Add(this.lblMethod); + this.pnlInputsCard.Controls.Add(this.cmbMethod); + this.pnlInputsCard.Controls.Add(this.lblMethodDesc); + this.pnlInputsCard.Controls.Add(this.lblEquation); + this.pnlInputsCard.Controls.Add(this.txtEquation); + this.pnlInputsCard.Controls.Add(this.lblVariable); + this.pnlInputsCard.Controls.Add(this.txtVariable); + this.pnlInputsCard.Controls.Add(this.lblInitialPoint); + this.pnlInputsCard.Controls.Add(this.txtInitialPoint); + this.pnlInputsCard.Controls.Add(this.lblMinX); + this.pnlInputsCard.Controls.Add(this.txtMinX); + this.pnlInputsCard.Controls.Add(this.lblMaxX); + this.pnlInputsCard.Controls.Add(this.txtMaxX); + this.pnlInputsCard.Controls.Add(this.lblIterations); + this.pnlInputsCard.Controls.Add(this.txtIterations); + this.pnlInputsCard.Controls.Add(this.btnFindRoot); + + // Hero Summary Card + this.pnlSummary.Location = new Point(24, 226); + this.pnlSummary.Size = new Size(860, 68); + this.pnlSummary.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlSummary.BackColor = Color.FromArgb(20, 30, 48); + this.pnlSummary.Padding = new Padding(16, 8, 16, 8); + + this.lblRootSummaryTitle.Text = "HESAPLANAN KÖK DEĞERİ"; + this.lblRootSummaryTitle.Location = new Point(16, 8); + this.lblRootSummaryTitle.AutoSize = true; + this.lblRootSummaryTitle.Font = new Font("Segoe UI Semibold", 8F, FontStyle.Bold); + this.lblRootSummaryTitle.ForeColor = Color.FromArgb(148, 163, 184); + + this.lblRootValue.Text = "x ≈ —"; + this.lblRootValue.Location = new Point(14, 25); + this.lblRootValue.AutoSize = true; + this.lblRootValue.Font = new Font("Consolas", 15F, FontStyle.Bold); + this.lblRootValue.ForeColor = Color.FromArgb(52, 211, 153); // Emerald 400 + + this.lblRootDetails.Text = "Henüz hesaplama yapılmadı. \"Kökü Hesapla\" butonuna basınız."; + this.lblRootDetails.Location = new Point(280, 29); + this.lblRootDetails.AutoSize = true; + this.lblRootDetails.Font = new Font("Segoe UI", 9F); + this.lblRootDetails.ForeColor = Color.FromArgb(203, 213, 225); + + this.btnCopyResult.Location = new Point(740, 18); + this.btnCopyResult.Anchor = AnchorStyles.Top | AnchorStyles.Right; + + this.pnlSummary.Controls.Add(this.lblRootSummaryTitle); + this.pnlSummary.Controls.Add(this.lblRootValue); + this.pnlSummary.Controls.Add(this.lblRootDetails); + this.pnlSummary.Controls.Add(this.btnCopyResult); + + // Log Label + this.lblLogTitle.Text = "📊 Detaylı İterasyon Adımları ve Hata Analizi:"; + this.lblLogTitle.Location = new Point(24, 302); + this.lblLogTitle.AutoSize = true; + this.lblLogTitle.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblLogTitle.ForeColor = ThemeHelper.LightText; + + // Log Text Box + this.txtResult.Location = new Point(24, 324); + this.txtResult.Size = new Size(860, 240); + this.txtResult.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + this.txtResult.BackColor = Color.FromArgb(15, 23, 42); + this.txtResult.BorderStyle = BorderStyle.FixedSingle; + this.txtResult.ForeColor = Color.FromArgb(186, 230, 253); this.txtResult.Multiline = true; - this.txtResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.txtResult.Font = new System.Drawing.Font("Consolas", 10F); + this.txtResult.ReadOnly = true; + this.txtResult.ScrollBars = ScrollBars.Vertical; + this.txtResult.Font = new Font("Consolas", 9.5F); - // - // RootFinderControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); + this.pnlContent.Controls.Add(this.pnlPresets); + this.pnlContent.Controls.Add(this.pnlInputsCard); + this.pnlContent.Controls.Add(this.pnlSummary); + this.pnlContent.Controls.Add(this.lblLogTitle); + this.pnlContent.Controls.Add(this.txtResult); + + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; this.Controls.Add(this.pnlContent); - this.Controls.Add(this.lblTitle); + this.Controls.Add(this.pnlHeader); this.Name = "RootFinderControl"; - this.Size = new System.Drawing.Size(800, 600); + this.Size = new Size(910, 680); + + this.pnlSummary.ResumeLayout(false); + this.pnlSummary.PerformLayout(); + this.pnlInputsCard.ResumeLayout(false); + this.pnlInputsCard.PerformLayout(); this.pnlContent.ResumeLayout(false); this.pnlContent.PerformLayout(); this.ResumeLayout(false); - } - private System.Windows.Forms.Label lblTitle; - private System.Windows.Forms.Panel pnlContent; - private System.Windows.Forms.Label lblMethod; - public System.Windows.Forms.ComboBox cmbMethod; - private System.Windows.Forms.Label lblEquation; - public System.Windows.Forms.TextBox txtEquation; - private System.Windows.Forms.Label lblVariable; - public System.Windows.Forms.TextBox txtVariable; - private System.Windows.Forms.Label lblInitialPoint; - public System.Windows.Forms.TextBox txtInitialPoint; - private System.Windows.Forms.Label lblMinX; - public System.Windows.Forms.TextBox txtMinX; - private System.Windows.Forms.Label lblMaxX; - public System.Windows.Forms.TextBox txtMaxX; - private System.Windows.Forms.Label lblIterations; - public System.Windows.Forms.TextBox txtIterations; - public System.Windows.Forms.Button btnFindRoot; - private System.Windows.Forms.Label lblResult; - public System.Windows.Forms.TextBox txtResult; + private Panel pnlHeader; + private Panel pnlContent; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnEx1; + private Button btnEx2; + private Button btnEx3; + + private Panel pnlInputsCard; + private Label lblMethod; + public ComboBox cmbMethod; + private Label lblMethodDesc; + private Label lblEquation; + public TextBox txtEquation; + private Label lblVariable; + public TextBox txtVariable; + private Label lblInitialPoint; + public TextBox txtInitialPoint; + private Label lblMinX; + public TextBox txtMinX; + private Label lblMaxX; + public TextBox txtMaxX; + private Label lblIterations; + public TextBox txtIterations; + public Button btnFindRoot; + + private Panel pnlSummary; + private Label lblRootSummaryTitle; + private Label lblRootValue; + private Label lblRootDetails; + private Button btnCopyResult; + + private Label lblLogTitle; + public TextBox txtResult; } } diff --git a/MathApp/MathApp/Controls/RootFinderControl.cs b/MathApp/MathApp/Controls/RootFinderControl.cs index 7dbb85a..53793d5 100644 --- a/MathApp/MathApp/Controls/RootFinderControl.cs +++ b/MathApp/MathApp/Controls/RootFinderControl.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Drawing; +using System.Globalization; using System.Windows.Forms; namespace MathApp.Controls @@ -13,67 +15,180 @@ namespace MathApp.Controls UpdateVisibility(); cmbMethod.SelectedIndexChanged += (s, e) => UpdateVisibility(); btnFindRoot.Click += BtnFindRoot_Click; + + btnEx1.Click += (s, e) => LoadPreset("x^3 - x - 2", "x", 0, "1.5", "1", "2"); + btnEx2.Click += (s, e) => LoadPreset("cos(x) - x", "x", 1, "0.5", "0", "1"); + btnEx3.Click += (s, e) => LoadPreset("e^x - 3*x", "x", 2, "0.5", "0", "1"); + + btnCopyResult.Click += (s, e) => { + if (!string.IsNullOrEmpty(txtResult.Text)) + { + Clipboard.SetText(txtResult.Text); + MessageBox.Show("Sonuç ve iterasyon adımları panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + // Enter key triggers search + txtEquation.KeyDown += Input_KeyDown; + txtInitialPoint.KeyDown += Input_KeyDown; + txtMinX.KeyDown += Input_KeyDown; + txtMaxX.KeyDown += Input_KeyDown; + txtIterations.KeyDown += Input_KeyDown; + } + + private void Input_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + e.SuppressKeyPress = true; + BtnFindRoot_Click(this, EventArgs.Empty); + } + } + + private void LoadPreset(string eq, string varName, int methodIdx, string initPt, string minX, string maxX) + { + txtEquation.Text = eq; + txtVariable.Text = varName; + cmbMethod.SelectedIndex = methodIdx; + txtInitialPoint.Text = initPt; + txtMinX.Text = minX; + txtMaxX.Text = maxX; + BtnFindRoot_Click(this, EventArgs.Empty); } private void UpdateVisibility() { - string method = cmbMethod.SelectedItem?.ToString() ?? ""; - bool isBracket = method == "Bisection" || method == "Regula Falsi"; - - lblInitialPoint.Visible = !isBracket; - txtInitialPoint.Visible = !isBracket; - - lblMinX.Visible = isBracket; - txtMinX.Visible = isBracket; - lblMaxX.Visible = isBracket; - txtMaxX.Visible = isBracket; + int idx = cmbMethod.SelectedIndex; + bool isSinglePoint = (idx == 0); // Newton-Raphson + + lblInitialPoint.Visible = isSinglePoint; + txtInitialPoint.Visible = isSinglePoint; + + lblMinX.Visible = !isSinglePoint; + txtMinX.Visible = !isSinglePoint; + lblMaxX.Visible = !isSinglePoint; + txtMaxX.Visible = !isSinglePoint; + + switch (idx) + { + case 0: + lblMethodDesc.Text = "💡 Fonksiyonun analitik türevi ile teğet çizerek hızlıca köke ulaşır. Tek bir başlangıç tahmini (x₀) yeterlidir."; + break; + case 1: + lblMethodDesc.Text = "💡 [a, b] aralığında f(a)·f(b) < 0 ise kökü bulmayı garanti eder. Güvenli ve kararlıdır."; + lblMinX.Text = "Alt Sınır (a):"; + lblMaxX.Text = "Üst Sınır (b):"; + break; + case 2: + lblMethodDesc.Text = "💡 Türev almadan iki nokta arasındaki kiriş eğimi ile yaklaşır. İki başlangıç tahmini (x₀, x₁) ister."; + lblMinX.Text = "Başlangıç 1 (x₀):"; + lblMaxX.Text = "Başlangıç 2 (x₁):"; + break; + case 3: + lblMethodDesc.Text = "💡 Doğrusal interpolasyon ile aralığı daraltarak köke ulaşır. [a, b] aralığı ister."; + lblMinX.Text = "Alt Sınır (a):"; + lblMaxX.Text = "Üst Sınır (b):"; + break; + } + } + + private decimal ParseDecimal(string input, string fieldName) + { + string norm = (input ?? "").Trim().Replace(',', '.'); + if (decimal.TryParse(norm, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) + return val; + throw new ArgumentException($"'{fieldName}' alanı için geçerli bir sayı giriniz."); } private void BtnFindRoot_Click(object sender, EventArgs e) { try { - string eq = txtEquation.Text; - string variable = txtVariable.Text; - int iterCount = 100; - int.TryParse(txtIterations.Text, out iterCount); - string method = cmbMethod.SelectedItem.ToString(); - - List logs = new List(); + string eq = txtEquation.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) + { + txtResult.Text = "Lütfen bir denklem giriniz (Örn: x^3 - x - 2)."; + lblRootValue.Text = "x ≈ —"; + lblRootDetails.Text = "Lütfen denklem giriniz."; + return; + } - if (method == "Newton-Raphson") + string variable = string.IsNullOrWhiteSpace(txtVariable.Text) ? "x" : txtVariable.Text.Trim(); + if (!int.TryParse(txtIterations.Text.Trim(), out int iterCount) || iterCount < 1) + iterCount = 50; + + int idx = cmbMethod.SelectedIndex; + List logs; + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + try { - decimal initialP = decimal.Parse(txtInitialPoint.Text); - logs = NumericalMethods.Method_NewtonRaphson(eq, initialP, iterCount); + if (idx == 0) // Newton-Raphson + { + decimal initialP = ParseDecimal(txtInitialPoint.Text, "Başlangıç Noktası (x₀)"); + logs = NumericalMethods.Method_NewtonRaphson(eq, initialP, iterCount, variable); + } + else if (idx == 1) // Bisection + { + 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); + } + else if (idx == 2) // Secant + { + 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); + } + 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); + } } - else if (method == "Bisection") + finally { - decimal minX = decimal.Parse(txtMinX.Text); - decimal maxX = decimal.Parse(txtMaxX.Text); - logs = NumericalMethods.Method_Bisection(eq, minX, maxX, iterCount); - } - else if (method == "Secant") - { - decimal minX = decimal.Parse(txtMinX.Text); - decimal maxX = decimal.Parse(txtMaxX.Text); - logs = NumericalMethods.Method_Secant(eq, minX, maxX, iterCount); - } - else if (method == "Regula Falsi") - { - decimal minX = decimal.Parse(txtMinX.Text); - decimal maxX = decimal.Parse(txtMaxX.Text); - logs = NumericalMethods.Method_RegulaFalsi(eq, minX, maxX, iterCount); - } - else - { - logs = new List { method + " method not yet active." }; + Function.UseRadians = prevRad; } 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(); + int parenIdx = displayRoot.IndexOf('('); + if (parenIdx > 0) displayRoot = displayRoot.Substring(0, parenIdx).Trim(); + lblRootValue.Text = displayRoot; + lblRootDetails.Text = $"✅ {logs.Count} iterasyon adımında başarıyla hesaplandı."; + lblRootValue.ForeColor = Color.FromArgb(52, 211, 153); + } + else if (logs.Count > 0) + { + lblRootValue.Text = "Tamamlandı"; + lblRootDetails.Text = $"İterasyonlar tamamlandı ({logs.Count} adım)."; + lblRootValue.ForeColor = Color.FromArgb(56, 189, 248); + } } catch (Exception ex) { - txtResult.Text = "Error: " + ex.Message; + txtResult.Text = "❌ Hata: " + ex.Message; + lblRootValue.Text = "Hata Oluştu"; + lblRootValue.ForeColor = Color.FromArgb(239, 68, 68); + lblRootDetails.Text = ex.Message; } } } diff --git a/MathApp/MathApp/Controls/SimpleCalculatorControl.Designer.cs b/MathApp/MathApp/Controls/SimpleCalculatorControl.Designer.cs index 8bcbcab..f5a37c0 100644 --- a/MathApp/MathApp/Controls/SimpleCalculatorControl.Designer.cs +++ b/MathApp/MathApp/Controls/SimpleCalculatorControl.Designer.cs @@ -1,3 +1,6 @@ +using System; +using System.Drawing; +using System.Windows.Forms; namespace MathApp.Controls { @@ -16,61 +19,165 @@ namespace MathApp.Controls private void InitializeComponent() { - this.txtDisplay = new System.Windows.Forms.TextBox(); - this.pnlButtons = new System.Windows.Forms.TableLayoutPanel(); + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Bilimsel Hesap Makinesi", + "Yüksek hassasiyetli (128-bit Decimal) bilimsel ifadeler, trigonometri, logaritma ve işlem geçmişi."); + + this.pnlMain = new Panel(); + this.pnlLeft = new Panel(); + this.pnlRightHistory = new Panel(); + this.pnlDisplayCard = new Panel(); + this.lblExpressionHistory = new Label(); + this.txtDisplay = new TextBox(); + this.pnlToolbar = new Panel(); + this.btnAngleMode = new Button(); + this.lblKeyboardHint = new Label(); + this.pnlButtons = new TableLayoutPanel(); + + this.lblHistoryTitle = new Label(); + this.lstHistory = new ListBox(); + this.btnClearHistory = new Button(); + this.SuspendLayout(); + this.pnlMain.SuspendLayout(); + this.pnlLeft.SuspendLayout(); + this.pnlRightHistory.SuspendLayout(); + this.pnlDisplayCard.SuspendLayout(); + this.pnlToolbar.SuspendLayout(); - // - // txtDisplay - // - this.txtDisplay.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(32)))), ((int)(((byte)(32))))); - this.txtDisplay.BorderStyle = System.Windows.Forms.BorderStyle.None; - this.txtDisplay.Dock = System.Windows.Forms.DockStyle.Top; - this.txtDisplay.Font = new System.Drawing.Font("Segoe UI", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.txtDisplay.ForeColor = System.Drawing.Color.White; - this.txtDisplay.Location = new System.Drawing.Point(0, 0); - this.txtDisplay.Name = "txtDisplay"; + // pnlMain + this.pnlMain.Dock = DockStyle.Fill; + this.pnlMain.Padding = new Padding(20); + this.pnlMain.BackColor = ThemeHelper.DarkBackground; + this.pnlMain.Controls.Add(this.pnlLeft); + this.pnlMain.Controls.Add(this.pnlRightHistory); + + // pnlRightHistory + this.pnlRightHistory.Dock = DockStyle.Right; + this.pnlRightHistory.Width = 260; + this.pnlRightHistory.Padding = new Padding(14, 0, 0, 0); + this.pnlRightHistory.BackColor = ThemeHelper.DarkBackground; + + this.lblHistoryTitle.Dock = DockStyle.Top; + this.lblHistoryTitle.Height = 32; + this.lblHistoryTitle.Text = "📜 İşlem Geçmişi (Çift Tıkla)"; + this.lblHistoryTitle.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold); + this.lblHistoryTitle.ForeColor = ThemeHelper.LightText; + this.lblHistoryTitle.TextAlign = ContentAlignment.MiddleLeft; + + this.btnClearHistory.Dock = DockStyle.Bottom; + this.btnClearHistory.Height = 34; + this.btnClearHistory.Text = "Geçmişi Temizle"; + this.btnClearHistory.FlatStyle = FlatStyle.Flat; + this.btnClearHistory.BackColor = ThemeHelper.ButtonSecondary; + this.btnClearHistory.ForeColor = ThemeHelper.LightText; + this.btnClearHistory.Font = new Font("Segoe UI", 9.5F); + this.btnClearHistory.FlatAppearance.BorderSize = 0; + this.btnClearHistory.Cursor = Cursors.Hand; + + this.lstHistory.Dock = DockStyle.Fill; + this.lstHistory.BackColor = ThemeHelper.CardBackground; + this.lstHistory.ForeColor = Color.FromArgb(186, 230, 253); + this.lstHistory.BorderStyle = BorderStyle.FixedSingle; + this.lstHistory.Font = new Font("Consolas", 10.5F); + this.lstHistory.ItemHeight = 22; + + this.pnlRightHistory.Controls.Add(this.lstHistory); + this.pnlRightHistory.Controls.Add(this.btnClearHistory); + this.pnlRightHistory.Controls.Add(this.lblHistoryTitle); + + // pnlLeft + this.pnlLeft.Dock = DockStyle.Fill; + this.pnlLeft.BackColor = ThemeHelper.DarkBackground; + + // pnlDisplayCard + this.pnlDisplayCard.Dock = DockStyle.Top; + this.pnlDisplayCard.Height = 108; + this.pnlDisplayCard.BackColor = ThemeHelper.CardBackground; + this.pnlDisplayCard.Padding = new Padding(16, 10, 16, 10); + + this.lblExpressionHistory.Dock = DockStyle.Top; + this.lblExpressionHistory.Height = 24; + this.lblExpressionHistory.Text = "İfade giriniz veya klavyeyi kullanınız"; + this.lblExpressionHistory.Font = new Font("Consolas", 10.5F, FontStyle.Regular); + this.lblExpressionHistory.ForeColor = ThemeHelper.MutedText; + this.lblExpressionHistory.TextAlign = ContentAlignment.MiddleRight; + + this.txtDisplay.Dock = DockStyle.Fill; + this.txtDisplay.BackColor = ThemeHelper.CardBackground; + this.txtDisplay.BorderStyle = BorderStyle.None; + this.txtDisplay.Font = new Font("Segoe UI Semibold", 30F, FontStyle.Bold); + this.txtDisplay.ForeColor = Color.White; this.txtDisplay.ReadOnly = true; - this.txtDisplay.Size = new System.Drawing.Size(600, 64); - this.txtDisplay.TabIndex = 0; this.txtDisplay.Text = "0"; - this.txtDisplay.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + this.txtDisplay.TextAlign = HorizontalAlignment.Right; + + this.pnlDisplayCard.Controls.Add(this.txtDisplay); + this.pnlDisplayCard.Controls.Add(this.lblExpressionHistory); + + // pnlToolbar + this.pnlToolbar.Dock = DockStyle.Top; + this.pnlToolbar.Height = 46; + this.pnlToolbar.Padding = new Padding(0, 8, 0, 6); + this.pnlToolbar.BackColor = ThemeHelper.DarkBackground; + + this.btnAngleMode.Dock = DockStyle.Left; + this.btnAngleMode.Width = 220; + this.btnAngleMode.FlatStyle = FlatStyle.Flat; + this.btnAngleMode.BackColor = ThemeHelper.AccentBlue; + this.btnAngleMode.ForeColor = Color.White; + this.btnAngleMode.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.btnAngleMode.FlatAppearance.BorderSize = 0; + this.btnAngleMode.Cursor = Cursors.Hand; + + this.lblKeyboardHint.Dock = DockStyle.Fill; + this.lblKeyboardHint.Text = "💡 Klavye kısayolları aktif: Sayılar, +, -, *, /, Enter (=), Backspace (Sil), Esc (AC)"; + this.lblKeyboardHint.Font = new Font("Segoe UI", 9F); + this.lblKeyboardHint.ForeColor = ThemeHelper.MutedText; + this.lblKeyboardHint.TextAlign = ContentAlignment.MiddleRight; + + this.pnlToolbar.Controls.Add(this.lblKeyboardHint); + this.pnlToolbar.Controls.Add(this.btnAngleMode); - // // pnlButtons - // - this.pnlButtons.ColumnCount = 4; - this.pnlButtons.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); - this.pnlButtons.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); - this.pnlButtons.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); - this.pnlButtons.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); - this.pnlButtons.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlButtons.Location = new System.Drawing.Point(0, 64); - this.pnlButtons.Name = "pnlButtons"; - this.pnlButtons.RowCount = 5; - this.pnlButtons.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); - this.pnlButtons.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); - this.pnlButtons.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); - this.pnlButtons.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); - this.pnlButtons.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); - this.pnlButtons.Size = new System.Drawing.Size(600, 536); - this.pnlButtons.TabIndex = 1; + this.pnlButtons.Dock = DockStyle.Fill; + this.pnlButtons.BackColor = ThemeHelper.DarkBackground; + + this.pnlLeft.Controls.Add(this.pnlButtons); + this.pnlLeft.Controls.Add(this.pnlToolbar); + this.pnlLeft.Controls.Add(this.pnlDisplayCard); - // // SimpleCalculatorControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); - this.Controls.Add(this.pnlButtons); - this.Controls.Add(this.txtDisplay); + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; + this.Controls.Add(this.pnlMain); + this.Controls.Add(this.pnlHeader); this.Name = "SimpleCalculatorControl"; - this.Size = new System.Drawing.Size(600, 600); + this.Size = new Size(880, 660); + + this.pnlToolbar.ResumeLayout(false); + this.pnlDisplayCard.ResumeLayout(false); + this.pnlDisplayCard.PerformLayout(); + this.pnlRightHistory.ResumeLayout(false); + this.pnlLeft.ResumeLayout(false); + this.pnlMain.ResumeLayout(false); this.ResumeLayout(false); - this.PerformLayout(); } - private System.Windows.Forms.TextBox txtDisplay; - private System.Windows.Forms.TableLayoutPanel pnlButtons; + private Panel pnlHeader; + private Panel pnlMain; + private Panel pnlLeft; + private Panel pnlRightHistory; + private Panel pnlDisplayCard; + private Label lblExpressionHistory; + private TextBox txtDisplay; + private Panel pnlToolbar; + private Button btnAngleMode; + private Label lblKeyboardHint; + private TableLayoutPanel pnlButtons; + private Label lblHistoryTitle; + private ListBox lstHistory; + private Button btnClearHistory; } } diff --git a/MathApp/MathApp/Controls/SimpleCalculatorControl.cs b/MathApp/MathApp/Controls/SimpleCalculatorControl.cs index 4253b87..04a54d4 100644 --- a/MathApp/MathApp/Controls/SimpleCalculatorControl.cs +++ b/MathApp/MathApp/Controls/SimpleCalculatorControl.cs @@ -1,5 +1,6 @@ using System; using System.Drawing; +using System.Globalization; using System.Windows.Forms; namespace MathApp.Controls @@ -13,76 +14,196 @@ namespace MathApp.Controls { InitializeComponent(); InitializeButtons(); + UpdateAngleButtonState(); + btnAngleMode.Click += BtnAngleMode_Click; + btnClearHistory.Click += (s, e) => lstHistory.Items.Clear(); + lstHistory.DoubleClick += LstHistory_DoubleClick; + } + + private void BtnAngleMode_Click(object sender, EventArgs e) + { + Function.UseRadians = !Function.UseRadians; + UpdateAngleButtonState(); + } + + private void UpdateAngleButtonState() + { + if (Function.UseRadians) + { + btnAngleMode.Text = "Açı Birimi: RAD (Radyan)"; + btnAngleMode.BackColor = Color.FromArgb(14, 165, 233); + } + else + { + btnAngleMode.Text = "Açı Birimi: DEG (Derece)"; + btnAngleMode.BackColor = Color.FromArgb(99, 102, 241); + } + } + + private void LstHistory_DoubleClick(object sender, EventArgs e) + { + if (lstHistory.SelectedItem != null) + { + string item = lstHistory.SelectedItem.ToString(); + int eqIdx = item.LastIndexOf('='); + if (eqIdx != -1 && eqIdx + 1 < item.Length) + { + string val = item.Substring(eqIdx + 1).Trim(); + currentExpression = val; + txtDisplay.Text = val; + lblExpressionHistory.Text = item.Substring(0, eqIdx).Trim() + " ="; + isResultShown = true; + } + } } private void InitializeButtons() { - // ... (Keeping initialization logic same, but for brevity I will rewrite it to ensure file integrity) - // Actually, I should preserve the exact logic. - // Re-implementing InitializeButtons to Match previous content exactly - - this.pnlButtons.RowCount = 5; - this.pnlButtons.RowStyles.Clear(); - for(int i=0; i<5; i++) this.pnlButtons.RowStyles.Add(new RowStyle(SizeType.Percent, 20F)); + pnlButtons.Controls.Clear(); + pnlButtons.ColumnCount = 6; + pnlButtons.RowCount = 7; + pnlButtons.ColumnStyles.Clear(); + pnlButtons.RowStyles.Clear(); - string[] gridLayout = { - "C", "(", ")", "/", - "7", "8", "9", "*", - "4", "5", "6", "-", - "1", "2", "3", "+", - "0", ".", "DEL", "=" + for (int c = 0; c < 6; c++) + pnlButtons.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / 6f)); + for (int r = 0; r < 7; r++) + pnlButtons.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / 7f)); + + string[] layout = { + // Row 0: Trig & Inverse Trig + "sin(", "cos(", "tan(", "cot(", "asin(", "acos(", + // Row 1: Hyperbolic, Inverse Tan & Logs + "sinh(", "cosh(", "tanh(", "atan(", "ln(", "log(", + // Row 2: Powers, Exp, Grouping + "sqrt(", "^", "exp(", "abs(", "(", ")", + // Row 3: Constants & Symbols + "pi", "e", "%", "DEL", "C", "/", + // Row 4: Digits 7,8,9, Ops + "7", "8", "9", "*", "-", "+", + // Row 5: Digits 4,5,6 + "4", "5", "6", "0", ".", "=", + // Row 6: Digits 1,2,3 + "1", "2", "3", "x", "y", "z" + }; + + // Let's arrange so the standard keypad is natural: + // Let's reorder rows 4, 5, 6: + // Row 3: pi, e, %, (, ), / + // Row 4: 7, 8, 9, *, DEL, C + // Row 5: 4, 5, 6, -, +, x + // Row 6: 1, 2, 3, 0, ., = + string[] standardKeypad = { + // Row 0: Trig + "sin(", "cos(", "tan(", "cot(", "asin(", "acos(", + // Row 1: Hyperbolic & Logs + "sinh(", "cosh(", "tanh(", "atan(", "ln(", "log(", + // Row 2: Roots, Powers & Constants + "sqrt(", "^", "exp(", "abs(", "pi", "e", + // Row 3: Grouping & Ops + "(", ")", "%", "DEL", "C", "/", + // Row 4: Keypad Row 1 + "7", "8", "9", "*", "-", "+", + // Row 5: Keypad Row 2 + "4", "5", "6", "x", "y", "z", + // Row 6: Keypad Row 3 & Action + "1", "2", "3", "0", ".", "=" }; int index = 0; - foreach (string text in gridLayout) + foreach (string text in standardKeypad) { - Button btn = new Button(); - btn.Text = text; - btn.Dock = DockStyle.Fill; - btn.FlatStyle = FlatStyle.Flat; - btn.FlatAppearance.BorderSize = 0; - btn.Font = new Font("Segoe UI", 18F, FontStyle.Regular, GraphicsUnit.Point); - btn.ForeColor = Color.White; + Button btn = new Button + { + Text = FormatButtonLabel(text), + Tag = text, + Dock = DockStyle.Fill, + FlatStyle = FlatStyle.Flat, + Margin = new Padding(3), + Font = new Font("Segoe UI Semibold", 11.5F, FontStyle.Bold, GraphicsUnit.Point), + ForeColor = Color.White, + Cursor = Cursors.Hand + }; + btn.FlatAppearance.BorderSize = 1; + btn.FlatAppearance.BorderColor = Color.FromArgb(51, 65, 85); btn.Click += Btn_Click; - - // Tag lookup for keyboard maybe? - btn.Tag = text; - if (IsOperator(text)) + if (text == "=") { - btn.BackColor = Color.FromArgb(40, 40, 40); - btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(60, 60, 60); - } - else if (text == "=") - { - btn.BackColor = Color.FromArgb(0, 120, 215); - btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 140, 240); + btn.BackColor = ThemeHelper.AccentBlue; + btn.FlatAppearance.MouseOverBackColor = ThemeHelper.AccentBlueHover; + btn.FlatAppearance.BorderColor = ThemeHelper.AccentBlueHover; } else if (text == "C" || text == "DEL") { - btn.BackColor = Color.FromArgb(50, 50, 50); - btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(70, 70, 70); + btn.BackColor = Color.FromArgb(127, 29, 29); + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(185, 28, 28); + btn.FlatAppearance.BorderColor = Color.FromArgb(153, 27, 27); + } + else if (IsOperator(text) || text == "^") + { + btn.BackColor = Color.FromArgb(51, 65, 85); + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(71, 85, 105); + } + else if (text.EndsWith("(") || text == "pi" || text == "e" || text == "(" || text == ")") + { + btn.BackColor = Color.FromArgb(30, 41, 59); + btn.ForeColor = Color.FromArgb(186, 230, 253); + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(51, 65, 85); + } + else if (text == "x" || text == "y" || text == "z") + { + btn.BackColor = Color.FromArgb(24, 38, 55); + btn.ForeColor = Color.FromArgb(250, 204, 21); + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(40, 58, 80); } else { - btn.BackColor = Color.FromArgb(30, 30, 30); - btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(50, 50, 50); + btn.BackColor = Color.FromArgb(15, 23, 42); + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(30, 41, 59); } - pnlButtons.Controls.Add(btn, index % 4, index / 4); + pnlButtons.Controls.Add(btn, index % 6, index / 6); index++; } } + private string FormatButtonLabel(string token) + { + return token switch + { + "sin(" => "sin", + "cos(" => "cos", + "tan(" => "tan", + "cot(" => "cot", + "asin(" => "sin⁻¹", + "acos(" => "cos⁻¹", + "atan(" => "tan⁻¹", + "sinh(" => "sinh", + "cosh(" => "cosh", + "tanh(" => "tanh", + "exp(" => "eˣ", + "^" => "xʸ", + "ln(" => "ln", + "log(" => "log₁₀", + "sqrt(" => "√x", + "abs(" => "|x|", + "pi" => "π", + "DEL" => "⌫ Sil", + "C" => "AC", + "*" => "×", + "/" => "÷", + _ => token + }; + } + private bool IsOperator(string text) { - return text == "+" || text == "-" || text == "*" || text == "/"; + return text == "+" || text == "-" || text == "*" || text == "/" || text == "^" || text == "%"; } - - // --- Keyboard Support --- + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - // Map keys string input = ""; bool handled = true; @@ -108,45 +229,40 @@ namespace MathApp.Controls case Keys.D8: input = "8"; break; case Keys.NumPad9: case Keys.D9: input = "9"; break; - + case Keys.Add: - case Keys.Oemplus: // Careful with Shift+= - input = "+"; break; + case Keys.Oemplus: + input = "+"; break; case Keys.Subtract: case Keys.OemMinus: input = "-"; break; case Keys.Multiply: input = "*"; break; case Keys.Divide: - case Keys.OemQuestion: // / + case Keys.OemQuestion: input = "/"; break; - + case Keys.Decimal: case Keys.OemPeriod: case Keys.Oemcomma: input = "."; break; - + case Keys.Back: case Keys.Delete: input = "DEL"; break; - + case Keys.Escape: input = "C"; break; case Keys.Enter: - case Keys.Return: input = "="; break; - - // Shift+8 (*) etc are handled by KeyChar usually vs Keys, - // but ProcessCmdKey sees Keys. - // For simplicity let's stick to Numpad and basics. - // Shift handling in ProcessCmdKey is tricky (keyData & Keys.Shift) + default: - // Check for shift combinations - if (keyData == (Keys.Shift | Keys.D8)) input = "*"; - else if (keyData == (Keys.Shift | Keys.D9)) input = "("; - else if (keyData == (Keys.Shift | Keys.D0)) input = ")"; - else if (keyData == (Keys.Shift | Keys.Oemplus)) input = "+"; + if (keyData == (Keys.Shift | Keys.D8)) input = "("; + else if (keyData == (Keys.Shift | Keys.D9)) input = ")"; + else if (keyData == (Keys.Shift | Keys.D0)) input = "="; + else if (keyData == (Keys.Shift | Keys.D3)) input = "^"; + else if (keyData == (Keys.Shift | Keys.Oemplus)) input = "+"; else handled = false; break; } @@ -162,16 +278,10 @@ namespace MathApp.Controls private void Btn_Click(object sender, EventArgs e) { - Button btn = sender as Button; - if (btn == null) return; - ProcessInput(btn.Text); - - // Remove focus from button so future key presses go to control/form? - // Actually ProcessCmdKey bubbles up so it's fine. - // But if button has focus, Enter triggers Click AND ProcessCmdKey might double trigger - // if we are not careful. - // ProcessCmdKey is called BEFORE key events. returning true eats it. - // So Enter won't click the focused button if we return true. + if (sender is Button btn && btn.Tag is string token) + { + ProcessInput(token); + } } private void ProcessInput(string text) @@ -180,6 +290,7 @@ namespace MathApp.Controls { currentExpression = ""; txtDisplay.Text = "0"; + lblExpressionHistory.Text = "İfade giriniz veya klavyeyi kullanınız"; isResultShown = false; } else if (text == "DEL") @@ -188,6 +299,7 @@ namespace MathApp.Controls { currentExpression = ""; txtDisplay.Text = "0"; + lblExpressionHistory.Text = ""; isResultShown = false; } else if (currentExpression.Length > 0) @@ -206,11 +318,11 @@ namespace MathApp.Controls { if (IsOperator(text)) { - isResultShown = false; // Continue with result + isResultShown = false; } else { - currentExpression = ""; // Start new + currentExpression = ""; isResultShown = false; } } @@ -221,31 +333,65 @@ namespace MathApp.Controls private void Evaluate() { + if (string.IsNullOrWhiteSpace(currentExpression)) return; + try { + string exprToEval = BalanceParentheses(currentExpression); Function f = new Function(); - f.Parse(currentExpression); + f.Parse(exprToEval); + if (f.Error) + { + lblExpressionHistory.Text = "Hata: " + f.ErrorDescription; + txtDisplay.Text = "Hata"; + isResultShown = true; + return; + } + f.Infix2Postfix(); f.EvaluatePostfix(); - - decimal result = f.m_result; - string resStr = result.ToString("G29", System.Globalization.CultureInfo.InvariantCulture); - + + if (f.Error) + { + lblExpressionHistory.Text = "Hata: " + f.ErrorDescription; + txtDisplay.Text = "Tanımsız"; + isResultShown = true; + return; + } + + decimal result = Math.Round(f.Result, 14); + string resStr = result.ToString("0.##############", CultureInfo.InvariantCulture); + + string historyEntry = $"{exprToEval} = {resStr}"; + lstHistory.Items.Insert(0, historyEntry); + + lblExpressionHistory.Text = exprToEval + " ="; txtDisplay.Text = resStr; currentExpression = resStr; isResultShown = true; } - catch (Exception) + catch (Exception ex) { - txtDisplay.Text = "Error"; + lblExpressionHistory.Text = "Hesaplama Hatası: " + ex.Message; + txtDisplay.Text = "Hata"; currentExpression = ""; - isResultShown = true; // allow typing to clear + isResultShown = true; } } - - private bool IsOperator(string text) // Redundant but kept for safety if used elsewhere - { - return text == "+" || text == "-" || text == "*" || text == "/"; + + private string BalanceParentheses(string expr) + { + int open = 0; + foreach (char c in expr) + { + if (c == '(') open++; + else if (c == ')') open--; + } + if (open > 0) + { + return expr + new string(')', open); + } + return expr; } } } diff --git a/MathApp/MathApp/Controls/SystemSolverControl.Designer.cs b/MathApp/MathApp/Controls/SystemSolverControl.Designer.cs index 4bffe2d..c46c69a 100644 --- a/MathApp/MathApp/Controls/SystemSolverControl.Designer.cs +++ b/MathApp/MathApp/Controls/SystemSolverControl.Designer.cs @@ -1,3 +1,5 @@ +using System.Drawing; +using System.Windows.Forms; namespace MathApp.Controls { @@ -7,159 +9,259 @@ namespace MathApp.Controls protected override void Dispose(bool disposing) { - if (disposing && (components != null)) - { - components.Dispose(); - } + if (disposing && (components != null)) components.Dispose(); base.Dispose(disposing); } private void InitializeComponent() { - this.lblTitle = new System.Windows.Forms.Label(); - this.pnlContent = new System.Windows.Forms.Panel(); + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Denklem Sistemi Çözücü (System Solver)", + "Newton-Raphson (Genel/Doğrusal Olmayan), Gauss-Seidel, LU Ayrışımı, Matris Tersi ve QR yöntemleriyle sistem çözümü."); - this.lblEqCount = new System.Windows.Forms.Label(); - this.numEqCount = new System.Windows.Forms.NumericUpDown(); - this.btnGenerate = new System.Windows.Forms.Button(); - this.pnlEquations = new System.Windows.Forms.FlowLayoutPanel(); - this.lblSystemIterations = new System.Windows.Forms.Label(); - this.txtSystemIterations = new System.Windows.Forms.TextBox(); - this.btnSolveSystem = new System.Windows.Forms.Button(); - this.lblSystemResult = new System.Windows.Forms.Label(); - this.txtSystemResult = new System.Windows.Forms.TextBox(); + this.pnlContent = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnExLinear = ThemeHelper.CreateExampleChip("Örnek 1: LU ile Doğrusal (2x+y=5, x-y=1)"); + this.btnExGaussSeidel = ThemeHelper.CreateExampleChip("Örnek 2: Gauss-Seidel (3x3)"); + this.btnExNonlinear = ThemeHelper.CreateExampleChip("Örnek 3: Newton-Raphson (x²+y²=4, x-y=0)"); + + this.pnlSettingsCard = new Panel(); + this.lblMethod = new Label(); + this.cmbSolverMethod = new ComboBox(); + this.lblMethodHint = new Label(); + this.lblEqCount = new Label(); + this.numEqCount = new NumericUpDown(); + this.btnGenerate = ThemeHelper.CreateActionButton("Boyut Değiştir", 110, 28, false); + this.lblSystemIterations = new Label(); + this.txtSystemIterations = new TextBox(); + this.btnSolveSystem = ThemeHelper.CreateActionButton("⚡ Sistemi Çöz", 160, 32, true); + + this.pnlEquations = new FlowLayoutPanel(); + + // Hero Solution Card + this.pnlSolutionHero = new Panel(); + this.lblHeroTitle = new Label(); + this.lblHeroSolution = new Label(); + this.lblHeroStatus = new Label(); + this.btnCopyHero = ThemeHelper.CreateCopyButton("📋 Çözümü Kopyala"); + + this.lblSystemResult = new Label(); + this.txtSystemResult = new TextBox(); this.pnlContent.SuspendLayout(); + this.pnlSettingsCard.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numEqCount)).BeginInit(); + this.pnlSolutionHero.SuspendLayout(); this.SuspendLayout(); - // - // lblTitle - // - this.lblTitle.Dock = System.Windows.Forms.DockStyle.Top; - this.lblTitle.Font = new System.Drawing.Font("Segoe UI Light", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.lblTitle.ForeColor = System.Drawing.Color.White; - this.lblTitle.Location = new System.Drawing.Point(0, 0); - this.lblTitle.Name = "lblTitle"; - this.lblTitle.Size = new System.Drawing.Size(800, 60); - this.lblTitle.TabIndex = 0; - this.lblTitle.Text = "Equation System Solver"; - this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.pnlContent.Dock = DockStyle.Fill; + this.pnlContent.BackColor = ThemeHelper.DarkBackground; + this.pnlContent.Padding = new Padding(24, 12, 24, 20); + this.pnlContent.AutoScroll = true; - // - // pnlContent - // - this.pnlContent.Controls.Add(this.txtSystemResult); - this.pnlContent.Controls.Add(this.lblSystemResult); - this.pnlContent.Controls.Add(this.btnSolveSystem); - this.pnlContent.Controls.Add(this.txtSystemIterations); - this.pnlContent.Controls.Add(this.lblSystemIterations); - this.pnlContent.Controls.Add(this.pnlEquations); - this.pnlContent.Controls.Add(this.btnGenerate); - this.pnlContent.Controls.Add(this.numEqCount); - this.pnlContent.Controls.Add(this.lblEqCount); - this.pnlContent.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlContent.Location = new System.Drawing.Point(0, 60); - this.pnlContent.Name = "pnlContent"; - this.pnlContent.Size = new System.Drawing.Size(800, 540); - this.pnlContent.TabIndex = 1; + // Presets + this.lblPresets.Text = "⚡ Hızlı Örnekler:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); - // Simple layout - int yObject = 20; - void StyleLabel(System.Windows.Forms.Label l) { - l.AutoSize = true; - l.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - l.ForeColor = System.Drawing.Color.White; - } + this.pnlPresets.Location = new Point(24, 10); + this.pnlPresets.Size = new Size(860, 32); + this.pnlPresets.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnExLinear); + this.pnlPresets.Controls.Add(this.btnExGaussSeidel); + this.pnlPresets.Controls.Add(this.btnExNonlinear); - StyleLabel(this.lblEqCount); - this.lblEqCount.Location = new System.Drawing.Point(20, yObject); - this.lblEqCount.Text = "Number of Equations:"; - - this.numEqCount.Location = new System.Drawing.Point(180, yObject); - this.numEqCount.Minimum = 1; + // Settings Card + this.pnlSettingsCard.Location = new Point(24, 46); + this.pnlSettingsCard.Size = new Size(860, 80); + this.pnlSettingsCard.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlSettingsCard.BackColor = ThemeHelper.CardBackground; + this.pnlSettingsCard.Padding = new Padding(14, 10, 14, 10); + + this.lblMethod.Text = "Çözücü:"; + this.lblMethod.Location = new Point(14, 12); + this.lblMethod.AutoSize = true; + this.lblMethod.Font = new Font("Segoe UI", 9F, FontStyle.Regular); + this.lblMethod.ForeColor = ThemeHelper.LightText; + + this.cmbSolverMethod.FormattingEnabled = true; + this.cmbSolverMethod.Items.AddRange(new object[] { + "Çok Değişkenli Newton-Raphson (Genel / Nonlineer)", + "Gauss-Seidel İterasyonu (Köşegen Baskın Doğrusal)", + "LU Ayrışımı (L·U·X = P·b Doğrusal — Hızlı)", + "Ters Matris Yöntemi (X = A⁻¹·b Doğrusal)", + "QR En Küçük Kareler Çözümü (Q·R·X = b)" + }); + this.cmbSolverMethod.Location = new Point(72, 8); + this.cmbSolverMethod.Size = new Size(330, 25); + this.cmbSolverMethod.Font = new Font("Segoe UI", 9F); + this.cmbSolverMethod.BackColor = Color.FromArgb(15, 23, 42); + this.cmbSolverMethod.ForeColor = Color.White; + this.cmbSolverMethod.DropDownStyle = ComboBoxStyle.DropDownList; + + this.lblEqCount.Text = "Denklem Sayısı:"; + this.lblEqCount.Location = new Point(415, 12); + this.lblEqCount.AutoSize = true; + this.lblEqCount.Font = new Font("Segoe UI", 9F, FontStyle.Regular); + this.lblEqCount.ForeColor = ThemeHelper.LightText; + + this.numEqCount.Location = new Point(510, 9); + this.numEqCount.Size = new Size(45, 25); + this.numEqCount.Minimum = 2; + this.numEqCount.Maximum = 6; this.numEqCount.Value = 2; - this.numEqCount.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.numEqCount.ForeColor = System.Drawing.Color.White; - this.numEqCount.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - - this.btnGenerate.Location = new System.Drawing.Point(310, yObject - 2); - this.btnGenerate.Text = "Generate"; - this.btnGenerate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnGenerate.BackColor = System.Drawing.Color.FromArgb(60, 60, 60); - this.btnGenerate.ForeColor = System.Drawing.Color.White; - this.btnGenerate.Size = new System.Drawing.Size(100, 25); - this.btnGenerate.FlatAppearance.BorderSize = 0; - yObject += 50; + this.numEqCount.BackColor = Color.FromArgb(15, 23, 42); + this.numEqCount.ForeColor = Color.White; - this.pnlEquations.Location = new System.Drawing.Point(20, yObject); - this.pnlEquations.Size = new System.Drawing.Size(750, 300); + this.btnGenerate.Location = new Point(562, 8); + + this.btnSolveSystem.Location = new Point(685, 6); + this.btnSolveSystem.Anchor = AnchorStyles.Top | AnchorStyles.Right; + + this.lblMethodHint.Location = new Point(14, 46); + this.lblMethodHint.Size = new Size(830, 24); + this.lblMethodHint.Font = new Font("Segoe UI", 8.5F); + this.lblMethodHint.ForeColor = Color.FromArgb(125, 211, 252); + this.lblMethodHint.Text = "💡 Yöntem ipucu burada görüntülenecektir."; + + this.lblSystemIterations.Text = "İterasyon:"; + this.lblSystemIterations.Location = new Point(680, 48); + this.lblSystemIterations.AutoSize = true; + this.lblSystemIterations.Font = new Font("Segoe UI", 8.5F); + this.lblSystemIterations.ForeColor = ThemeHelper.MutedText; + + this.txtSystemIterations.Location = new Point(745, 45); + this.txtSystemIterations.Size = new Size(45, 23); + this.txtSystemIterations.BackColor = Color.FromArgb(15, 23, 42); + this.txtSystemIterations.BorderStyle = BorderStyle.FixedSingle; + this.txtSystemIterations.ForeColor = Color.White; + this.txtSystemIterations.Font = new Font("Consolas", 9F); + this.txtSystemIterations.Text = "50"; + + this.pnlSettingsCard.Controls.Add(this.lblMethod); + this.pnlSettingsCard.Controls.Add(this.cmbSolverMethod); + this.pnlSettingsCard.Controls.Add(this.lblEqCount); + this.pnlSettingsCard.Controls.Add(this.numEqCount); + this.pnlSettingsCard.Controls.Add(this.btnGenerate); + this.pnlSettingsCard.Controls.Add(this.btnSolveSystem); + this.pnlSettingsCard.Controls.Add(this.lblMethodHint); + this.pnlSettingsCard.Controls.Add(this.lblSystemIterations); + this.pnlSettingsCard.Controls.Add(this.txtSystemIterations); + + // Equations panel + this.pnlEquations.Location = new Point(24, 132); + this.pnlEquations.Size = new Size(860, 115); + this.pnlEquations.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.pnlEquations.AutoScroll = true; - this.pnlEquations.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; - this.pnlEquations.WrapContents = false; - this.pnlEquations.BorderStyle = System.Windows.Forms.BorderStyle.None; - this.pnlEquations.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(25)))), ((int)(((byte)(25)))), ((int)(((byte)(25))))); - yObject += 320; - StyleLabel(this.lblSystemIterations); - this.lblSystemIterations.Location = new System.Drawing.Point(20, yObject); - this.lblSystemIterations.Text = "Iterations:"; - this.txtSystemIterations.Location = new System.Drawing.Point(100, yObject); - this.txtSystemIterations.Text = "100"; - this.txtSystemIterations.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtSystemIterations.ForeColor = System.Drawing.Color.White; - this.txtSystemIterations.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - yObject += 50; + // Hero Solution Card + this.pnlSolutionHero.Location = new Point(24, 252); + this.pnlSolutionHero.Size = new Size(860, 64); + this.pnlSolutionHero.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlSolutionHero.BackColor = Color.FromArgb(20, 30, 48); + this.pnlSolutionHero.Padding = new Padding(16, 8, 16, 8); - this.btnSolveSystem.Location = new System.Drawing.Point(20, yObject); - this.btnSolveSystem.Text = "Solve System"; - this.btnSolveSystem.Size = new System.Drawing.Size(150, 40); - this.btnSolveSystem.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnSolveSystem.BackColor = System.Drawing.Color.FromArgb(0, 120, 215); - this.btnSolveSystem.ForeColor = System.Drawing.Color.White; - this.btnSolveSystem.Font = new System.Drawing.Font("Segoe UI Semibold", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); - this.btnSolveSystem.FlatAppearance.BorderSize = 0; - yObject += 60; - - StyleLabel(this.lblSystemResult); - this.lblSystemResult.Location = new System.Drawing.Point(20, yObject); - this.lblSystemResult.Text = "Result:"; - this.txtSystemResult.Location = new System.Drawing.Point(100, yObject); - this.txtSystemResult.Size = new System.Drawing.Size(650, 100); + this.lblHeroTitle.Text = "SİSTEM ÇÖZÜM VEKTÖRÜ (X)"; + this.lblHeroTitle.Location = new Point(14, 8); + this.lblHeroTitle.AutoSize = true; + this.lblHeroTitle.Font = new Font("Segoe UI Semibold", 8F, FontStyle.Bold); + this.lblHeroTitle.ForeColor = Color.FromArgb(148, 163, 184); + + this.lblHeroSolution.Text = "X = [ — ]"; + this.lblHeroSolution.Location = new Point(12, 26); + this.lblHeroSolution.AutoSize = true; + this.lblHeroSolution.Font = new Font("Consolas", 14F, FontStyle.Bold); + this.lblHeroSolution.ForeColor = Color.FromArgb(52, 211, 153); + + this.lblHeroStatus.Text = "Henüz çözülmedi."; + this.lblHeroStatus.Location = new Point(320, 30); + this.lblHeroStatus.AutoSize = true; + this.lblHeroStatus.Font = new Font("Segoe UI", 9F); + this.lblHeroStatus.ForeColor = Color.FromArgb(203, 213, 225); + + this.btnCopyHero.Location = new Point(720, 18); + this.btnCopyHero.Anchor = AnchorStyles.Top | AnchorStyles.Right; + + this.pnlSolutionHero.Controls.Add(this.lblHeroTitle); + this.pnlSolutionHero.Controls.Add(this.lblHeroSolution); + this.pnlSolutionHero.Controls.Add(this.lblHeroStatus); + this.pnlSolutionHero.Controls.Add(this.btnCopyHero); + + // Detailed Result Log + this.lblSystemResult.Text = "📊 Detaylı Çözüm Adımları, Matris Formu ve Hata Analizi:"; + this.lblSystemResult.Location = new Point(24, 322); + this.lblSystemResult.AutoSize = true; + this.lblSystemResult.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblSystemResult.ForeColor = ThemeHelper.LightText; + + this.txtSystemResult.Location = new Point(24, 344); + this.txtSystemResult.Size = new Size(860, 230); + this.txtSystemResult.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + this.txtSystemResult.BackColor = Color.FromArgb(15, 23, 42); + this.txtSystemResult.BorderStyle = BorderStyle.FixedSingle; + this.txtSystemResult.ForeColor = Color.FromArgb(186, 230, 253); this.txtSystemResult.Multiline = true; - this.txtSystemResult.Font = new System.Drawing.Font("Consolas", 10F); - this.txtSystemResult.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30))))); - this.txtSystemResult.ForeColor = System.Drawing.Color.White; - this.txtSystemResult.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.txtSystemResult.ReadOnly = true; + this.txtSystemResult.ScrollBars = ScrollBars.Vertical; + this.txtSystemResult.Font = new Font("Consolas", 9.5F); + this.pnlContent.Controls.Add(this.pnlPresets); + this.pnlContent.Controls.Add(this.pnlSettingsCard); + this.pnlContent.Controls.Add(this.pnlEquations); + this.pnlContent.Controls.Add(this.pnlSolutionHero); + this.pnlContent.Controls.Add(this.lblSystemResult); + this.pnlContent.Controls.Add(this.txtSystemResult); - // - // SystemSolverControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; this.Controls.Add(this.pnlContent); - this.Controls.Add(this.lblTitle); + this.Controls.Add(this.pnlHeader); this.Name = "SystemSolverControl"; - this.Size = new System.Drawing.Size(800, 600); + this.Size = new Size(910, 680); + + this.pnlSettingsCard.ResumeLayout(false); + this.pnlSettingsCard.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numEqCount)).EndInit(); + this.pnlSolutionHero.ResumeLayout(false); + this.pnlSolutionHero.PerformLayout(); this.pnlContent.ResumeLayout(false); this.pnlContent.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.numEqCount)).EndInit(); this.ResumeLayout(false); - } - private System.Windows.Forms.Label lblTitle; - private System.Windows.Forms.Panel pnlContent; - private System.Windows.Forms.Label lblEqCount; - public System.Windows.Forms.NumericUpDown numEqCount; - public System.Windows.Forms.Button btnGenerate; - public System.Windows.Forms.FlowLayoutPanel pnlEquations; - private System.Windows.Forms.Label lblSystemIterations; - public System.Windows.Forms.TextBox txtSystemIterations; - public System.Windows.Forms.Button btnSolveSystem; - private System.Windows.Forms.Label lblSystemResult; - public System.Windows.Forms.TextBox txtSystemResult; + private Panel pnlHeader; + private Panel pnlContent; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnExLinear; + private Button btnExGaussSeidel; + private Button btnExNonlinear; + + private Panel pnlSettingsCard; + private Label lblMethod; + public ComboBox cmbSolverMethod; + private Label lblMethodHint; + private Label lblEqCount; + public NumericUpDown numEqCount; + public Button btnGenerate; + private Label lblSystemIterations; + public TextBox txtSystemIterations; + public Button btnSolveSystem; + + public FlowLayoutPanel pnlEquations; + + private Panel pnlSolutionHero; + private Label lblHeroTitle; + private Label lblHeroSolution; + private Label lblHeroStatus; + private Button btnCopyHero; + + private Label lblSystemResult; + public TextBox txtSystemResult; } } diff --git a/MathApp/MathApp/Controls/SystemSolverControl.cs b/MathApp/MathApp/Controls/SystemSolverControl.cs index d398df1..383d81b 100644 --- a/MathApp/MathApp/Controls/SystemSolverControl.cs +++ b/MathApp/MathApp/Controls/SystemSolverControl.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; using System.Drawing; +using System.Globalization; +using System.Linq; +using System.Text; using System.Windows.Forms; namespace MathApp.Controls @@ -14,33 +17,182 @@ namespace MathApp.Controls public SystemSolverControl() { InitializeComponent(); + cmbSolverMethod.SelectedIndex = 0; + UpdateMethodHint(); + cmbSolverMethod.SelectedIndexChanged += (s, e) => UpdateMethodHint(); + btnGenerate.Click += BtnGenerate_Click; btnSolveSystem.Click += BtnSolveSystem_Click; + + btnExLinear.Click += (s, e) => { + cmbSolverMethod.SelectedIndex = 2; // LU Decomposition + LoadPreset( + new[] { "2*x + y = 5", "x - y = 1" }, + new[] { "x", "y" }, + new[] { "0", "0" }); + }; + + btnExGaussSeidel.Click += (s, e) => { + cmbSolverMethod.SelectedIndex = 1; // Gauss-Seidel + LoadPreset( + new[] { "4*x + y - z = 7", "x - 5*y - z = -8", "2*x + y + 6*z = 9" }, + new[] { "x", "y", "z" }, + new[] { "0", "0", "0" }); + }; + + btnExNonlinear.Click += (s, e) => { + cmbSolverMethod.SelectedIndex = 0; // Newton-Raphson + LoadPreset( + new[] { "x^2 + y^2 - 4", "x - y" }, + new[] { "x", "y" }, + new[] { "1.5", "1.0" }); + }; + + btnCopyHero.Click += (s, e) => { + if (!string.IsNullOrEmpty(txtSystemResult.Text)) + { + Clipboard.SetText(txtSystemResult.Text); + MessageBox.Show("Sistem çözümü ve detayları panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + // Populate default 2 equations immediately on startup + LoadPreset( + new[] { "2*x + y = 5", "x - y = 1" }, + new[] { "x", "y" }, + new[] { "0", "0" }, + autoSolve: false); + } + + private void UpdateMethodHint() + { + switch (cmbSolverMethod.SelectedIndex) + { + case 0: + lblMethodHint.Text = "💡 Newton-Raphson: Doğrusal olmayan (polinom, trigonometrik, üstel) sistemler için teğet jakobiyen tabanlı genel çözücü. Başlangıç noktaları girilmelidir."; + break; + case 1: + lblMethodHint.Text = "💡 Gauss-Seidel: Doğrusal sistemler için ardışık iterasyon yöntemi. Köşegen baskınlık otomatik denetlenir ve satırlar sıralanır."; + break; + case 2: + lblMethodHint.Text = "💡 LU Ayrışımı: Doğrusal sistemler için A = P·L·U matris çarpanlarına ayırma ile doğrudan, kesin ve en hızlı çözücü."; + break; + case 3: + lblMethodHint.Text = "💡 Ters Matris: Doğrusal sistemlerde X = A⁻¹·b doğrudan ters matris formülü ile analitik çözüm sağlar."; + break; + case 4: + lblMethodHint.Text = "💡 QR Ayrışımı: Householder ortogonal dönüşümü ile kare veya aşırı belirlenmiş sistemler için en küçük kareler çözümü sunar."; + break; + } + } + + private void LoadPreset(string[] eqs, string[] vars, string[] inits, bool autoSolve = true) + { + numEqCount.Value = eqs.Length; + GenerateRows(eqs.Length, eqs, vars, inits); + if (autoSolve) + { + BtnSolveSystem_Click(this, EventArgs.Empty); + } } private void BtnGenerate_Click(object sender, EventArgs e) { + int count = (int)numEqCount.Value; + string[] defaultVars = { "x", "y", "z", "w", "u", "v", "t", "s" }; + string[] eqs = new string[count]; + string[] vars = new string[count]; + string[] inits = new string[count]; + + for (int i = 0; i < count; i++) + { + eqs[i] = i < equationsInputs.Count ? equationsInputs[i].Text : ""; + vars[i] = i < variablesInputs.Count ? variablesInputs[i].Text : (i < defaultVars.Length ? defaultVars[i] : "x" + (i + 1)); + inits[i] = i < initialPointsInputs.Count ? initialPointsInputs[i].Text : "1"; + } + + GenerateRows(count, eqs, vars, inits); + } + + private void GenerateRows(int count, string[] eqs, string[] vars, string[] inits) + { + pnlEquations.SuspendLayout(); pnlEquations.Controls.Clear(); equationsInputs.Clear(); variablesInputs.Clear(); initialPointsInputs.Clear(); - int count = (int)numEqCount.Value; - for (int i = 0; i < count; i++) { - Panel p = new Panel(); - p.Size = new Size(720, 30); - p.BackColor = Color.FromArgb(30,30,30); - - Label lblEq = new Label { Text = "Eq " + (i+1), Location = new Point(0, 5), AutoSize = true, ForeColor = Color.White }; - TextBox txtEq = new TextBox { Location = new Point(50, 3), Size = new Size(300, 23), BackColor = Color.FromArgb(40,40,40), ForeColor = Color.White, BorderStyle = BorderStyle.FixedSingle }; - - Label lblVar = new Label { Text = "Var", Location = new Point(360, 5), AutoSize = true, ForeColor = Color.White }; - TextBox txtVar = new TextBox { Location = new Point(390, 3), Size = new Size(50, 23), BackColor = Color.FromArgb(40,40,40), ForeColor = Color.White, BorderStyle = BorderStyle.FixedSingle }; - - Label lblInit = new Label { Text = "Init", Location = new Point(450, 5), AutoSize = true, ForeColor = Color.White }; - TextBox txtInit = new TextBox { Location = new Point(480, 3), Size = new Size(50, 23), Text="0", BackColor = Color.FromArgb(40,40,40), ForeColor = Color.White, BorderStyle = BorderStyle.FixedSingle }; + Panel p = new Panel + { + Size = new Size(820, 36), + BackColor = ThemeHelper.CardBackground, + Margin = new Padding(0, 0, 0, 4) + }; + + Label lblEq = new Label + { + Text = $"Denklem {i + 1}:", + Location = new Point(8, 9), + Size = new Size(78, 20), + ForeColor = ThemeHelper.LightText, + Font = new Font("Segoe UI", 9F) + }; + + TextBox txtEq = new TextBox + { + Location = new Point(90, 6), + Size = new Size(330, 24), + BackColor = Color.FromArgb(15, 23, 42), + BorderStyle = BorderStyle.FixedSingle, + ForeColor = Color.White, + Font = new Font("Consolas", 10F), + Text = (eqs != null && i < eqs.Length) ? eqs[i] : "" + }; + txtEq.KeyDown += Input_KeyDown; + + Label lblVar = new Label + { + Text = "Değişken:", + Location = new Point(430, 9), + Size = new Size(62, 20), + ForeColor = ThemeHelper.LightText, + Font = new Font("Segoe UI", 8.5F) + }; + + TextBox txtVar = new TextBox + { + Location = new Point(494, 6), + Size = new Size(50, 24), + BackColor = Color.FromArgb(15, 23, 42), + BorderStyle = BorderStyle.FixedSingle, + ForeColor = Color.White, + Font = new Font("Consolas", 10F), + Text = (vars != null && i < vars.Length) ? vars[i] : ("x" + (i + 1)) + }; + txtVar.KeyDown += Input_KeyDown; + + Label lblInit = new Label + { + Text = "Başlangıç (x₀):", + Location = new Point(554, 9), + Size = new Size(88, 20), + ForeColor = ThemeHelper.LightText, + Font = new Font("Segoe UI", 8.5F) + }; + + TextBox txtInit = new TextBox + { + Location = new Point(644, 6), + Size = new Size(70, 24), + BackColor = Color.FromArgb(15, 23, 42), + BorderStyle = BorderStyle.FixedSingle, + ForeColor = Color.White, + Font = new Font("Consolas", 10F), + Text = (inits != null && i < inits.Length) ? inits[i] : "1" + }; + txtInit.KeyDown += Input_KeyDown; p.Controls.Add(lblEq); p.Controls.Add(txtEq); @@ -49,11 +201,22 @@ namespace MathApp.Controls p.Controls.Add(lblInit); p.Controls.Add(txtInit); - pnlEquations.Controls.Add(p); - equationsInputs.Add(txtEq); variablesInputs.Add(txtVar); initialPointsInputs.Add(txtInit); + + pnlEquations.Controls.Add(p); + } + + pnlEquations.ResumeLayout(); + } + + private void Input_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + e.SuppressKeyPress = true; + BtnSolveSystem_Click(this, EventArgs.Empty); } } @@ -61,47 +224,123 @@ namespace MathApp.Controls { try { + int count = equationsInputs.Count; + if (count == 0) return; + List eqs = new List(); Dictionary dict = new Dictionary(); - - for(int i=0; i results; + List stepLogs; + try + { + if (methodIdx == 0) // Multivariable Newton-Raphson + { + results = NumericalMethods.SolveEquationSystemWithLogs(eqs, dict, iterCount, out stepLogs); + } + else if (methodIdx == 1) // Gauss-Seidel + { + results = NumericalMethods.Method_GaussSeidel(eqs, dict, iterCount, out stepLogs); + } + 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; + } - Dictionary results = NumericalMethods.MethodMultiVar_SolveEquationSystem(eqs, dict, iterCount); - if (results != null) { List resLines = new List(); - foreach(var kvp in results) + resLines.Add("=== ÇÖZÜM SONUÇLARI ==="); + StringBuilder heroSb = new StringBuilder(); + int k = 0; + foreach (var kvp in results) { - resLines.Add(kvp.Key + ": " + kvp.Value.ToString("F8")); + decimal rounded = Math.Round(kvp.Value, 8); + string valStr = rounded.ToString("0.########", CultureInfo.InvariantCulture); + resLines.Add($" {kvp.Key} = {valStr}"); + + if (k > 0) heroSb.Append(", "); + heroSb.Append($"{kvp.Key} = {valStr}"); + k++; } + + lblHeroSolution.Text = heroSb.ToString(); + lblHeroSolution.ForeColor = Color.FromArgb(52, 211, 153); + lblHeroStatus.Text = $"✅ {results.Count} değişkenli sistem başarıyla çözüldü."; + + resLines.Add(""); + resLines.Add("=== DETAYLI ÇÖZÜM ADIMLARI ==="); + resLines.AddRange(stepLogs); + txtSystemResult.Text = string.Join(Environment.NewLine, resLines); } else - txtSystemResult.Text = "Failed to solve."; + { + lblHeroSolution.Text = "Çözüm Bulunamadı"; + lblHeroSolution.ForeColor = Color.FromArgb(239, 68, 68); + lblHeroStatus.Text = "Belirtilen tolerans ve iterasyon sınırında sistem çözülemedi."; + txtSystemResult.Text = "Sistem çözülemedi."; + } } catch (Exception ex) { - txtSystemResult.Text = "Error: " + ex.Message; + lblHeroSolution.Text = "Hata Oluştu"; + lblHeroSolution.ForeColor = Color.FromArgb(239, 68, 68); + lblHeroStatus.Text = ex.Message; + txtSystemResult.Text = "❌ Hata: " + ex.Message; } } } diff --git a/MathApp/MathApp/Controls/TaylorSeriesControl.Designer.cs b/MathApp/MathApp/Controls/TaylorSeriesControl.Designer.cs index deb5520..af90064 100644 --- a/MathApp/MathApp/Controls/TaylorSeriesControl.Designer.cs +++ b/MathApp/MathApp/Controls/TaylorSeriesControl.Designer.cs @@ -1,3 +1,5 @@ +using System.Drawing; +using System.Windows.Forms; namespace MathApp.Controls { @@ -16,162 +18,213 @@ namespace MathApp.Controls private void InitializeComponent() { - this.lblTitle = new System.Windows.Forms.Label(); - this.pnlContent = new System.Windows.Forms.Panel(); - - this.lblFunction = new System.Windows.Forms.Label(); - this.txtFunction = new System.Windows.Forms.TextBox(); - this.lblVariable = new System.Windows.Forms.Label(); - this.txtVariable = new System.Windows.Forms.TextBox(); - this.lblCenterPoint = new System.Windows.Forms.Label(); - this.txtCenterPoint = new System.Windows.Forms.TextBox(); - this.lblOrder = new System.Windows.Forms.Label(); - this.numOrder = new System.Windows.Forms.NumericUpDown(); - this.btnCalculate = new System.Windows.Forms.Button(); - this.lblResult = new System.Windows.Forms.Label(); - this.txtResult = new System.Windows.Forms.TextBox(); + this.pnlHeader = ThemeHelper.CreateHeaderPanel( + "Taylor Serisi Hesaplayıcı (Tek Değişkenli)", + "Bir f(x) fonksiyonunun verilen a merkez noktasındaki n. dereceden Taylor / Maclaurin polinom açılımı ve türev katsayıları."); + + this.pnlContent = new Panel(); + this.pnlPresets = new FlowLayoutPanel(); + this.lblPresets = new Label(); + this.btnExSin = ThemeHelper.CreateExampleChip("Örnek 1: sin(x) (a=0, n=5)"); + this.btnExExp = ThemeHelper.CreateExampleChip("Örnek 2: exp(x) (a=0, n=4)"); + this.btnExLn = ThemeHelper.CreateExampleChip("Örnek 3: ln(x) (a=1, n=4)"); + + this.pnlInputCard = new Panel(); + this.lblFunction = new Label(); + this.txtFunction = new TextBox(); + this.lblVariable = new Label(); + this.txtVariable = new TextBox(); + this.lblCenterPoint = new Label(); + this.txtCenterPoint = new TextBox(); + this.lblOrder = new Label(); + this.numOrder = new NumericUpDown(); + this.btnCalculate = ThemeHelper.CreateActionButton("📐 Taylor Polinomunu Hesapla", 220, 36, true); + + // Hero Polynomial Card + this.pnlHeroPoly = new Panel(); + this.lblHeroPolyTitle = new Label(); + this.lblHeroPolyValue = new Label(); + this.btnCopyPoly = ThemeHelper.CreateCopyButton("📋 Polinomu Kopyala"); + + this.lblResult = new Label(); + this.txtResult = new TextBox(); this.pnlContent.SuspendLayout(); + this.pnlInputCard.SuspendLayout(); + this.pnlHeroPoly.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numOrder)).BeginInit(); this.SuspendLayout(); - // - // lblTitle - // - this.lblTitle.Dock = System.Windows.Forms.DockStyle.Top; - this.lblTitle.Font = new System.Drawing.Font("Segoe UI Light", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.lblTitle.ForeColor = System.Drawing.Color.White; - this.lblTitle.Location = new System.Drawing.Point(0, 0); - this.lblTitle.Name = "lblTitle"; - this.lblTitle.Size = new System.Drawing.Size(800, 60); - this.lblTitle.TabIndex = 0; - this.lblTitle.Text = "Taylor Series Calculator"; - this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.pnlContent.Dock = DockStyle.Fill; + this.pnlContent.BackColor = ThemeHelper.DarkBackground; + this.pnlContent.Padding = new Padding(24, 12, 24, 20); + this.pnlContent.AutoScroll = true; - // - // pnlContent - // - this.pnlContent.Controls.Add(this.txtResult); - this.pnlContent.Controls.Add(this.lblResult); - this.pnlContent.Controls.Add(this.btnCalculate); - this.pnlContent.Controls.Add(this.numOrder); - this.pnlContent.Controls.Add(this.lblOrder); - this.pnlContent.Controls.Add(this.txtCenterPoint); - this.pnlContent.Controls.Add(this.lblCenterPoint); - this.pnlContent.Controls.Add(this.txtVariable); - this.pnlContent.Controls.Add(this.lblVariable); - this.pnlContent.Controls.Add(this.txtFunction); - this.pnlContent.Controls.Add(this.lblFunction); - this.pnlContent.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlContent.Location = new System.Drawing.Point(0, 60); - this.pnlContent.Name = "pnlContent"; - this.pnlContent.Size = new System.Drawing.Size(800, 540); - this.pnlContent.TabIndex = 1; + // Presets + this.lblPresets.Text = "⚡ Hızlı Örnekler:"; + this.lblPresets.AutoSize = true; + this.lblPresets.ForeColor = ThemeHelper.MutedText; + this.lblPresets.Font = new Font("Segoe UI Semibold", 9F, FontStyle.Bold); + this.lblPresets.Margin = new Padding(0, 5, 8, 0); - int yObject = 20; + this.pnlPresets.Location = new Point(24, 10); + this.pnlPresets.Size = new Size(860, 32); + this.pnlPresets.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlPresets.Controls.Add(this.lblPresets); + this.pnlPresets.Controls.Add(this.btnExSin); + this.pnlPresets.Controls.Add(this.btnExExp); + this.pnlPresets.Controls.Add(this.btnExLn); - void StyleLabel(System.Windows.Forms.Label l) { + // Input Card + this.pnlInputCard.Location = new Point(24, 46); + this.pnlInputCard.Size = new Size(860, 96); + this.pnlInputCard.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlInputCard.BackColor = ThemeHelper.CardBackground; + this.pnlInputCard.Padding = new Padding(14, 10, 14, 10); + + void StyleLabel(Label l, string text, Point loc) + { + l.Text = text; + l.Location = loc; l.AutoSize = true; - l.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - l.ForeColor = System.Drawing.Color.White; + l.Font = new Font("Segoe UI", 9F, FontStyle.Regular); + l.ForeColor = ThemeHelper.LightText; } - StyleLabel(this.lblFunction); - this.lblFunction.Location = new System.Drawing.Point(20, yObject); - this.lblFunction.Text = "Function f(x):"; - - this.txtFunction.Location = new System.Drawing.Point(150, yObject); - this.txtFunction.Size = new System.Drawing.Size(400, 25); - this.txtFunction.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtFunction.ForeColor = System.Drawing.Color.White; - this.txtFunction.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - yObject += 50; + void StyleInput(TextBox t, string def, Point loc, Size sz) + { + t.Location = loc; + t.Size = sz; + t.BackColor = Color.FromArgb(15, 23, 42); + t.BorderStyle = BorderStyle.FixedSingle; + t.ForeColor = Color.White; + t.Font = new Font("Consolas", 10.5F); + t.Text = def; + } - StyleLabel(this.lblVariable); - this.lblVariable.Location = new System.Drawing.Point(20, yObject); - this.lblVariable.Text = "Variable (e.g. x):"; - this.txtVariable.Location = new System.Drawing.Point(150, yObject); - this.txtVariable.Size = new System.Drawing.Size(100, 25); - this.txtVariable.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtVariable.ForeColor = System.Drawing.Color.White; - this.txtVariable.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtVariable.Text = "x"; - yObject += 50; + StyleLabel(this.lblFunction, "Fonksiyon f(x):", new Point(14, 16)); + StyleInput(this.txtFunction, "sin(x)", new Point(110, 13), new Size(320, 26)); - StyleLabel(this.lblCenterPoint); - this.lblCenterPoint.Location = new System.Drawing.Point(20, yObject); - this.lblCenterPoint.Text = "Center Point (a):"; - this.txtCenterPoint.Location = new System.Drawing.Point(150, yObject); - this.txtCenterPoint.Size = new System.Drawing.Size(100, 25); - this.txtCenterPoint.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.txtCenterPoint.ForeColor = System.Drawing.Color.White; - this.txtCenterPoint.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.txtCenterPoint.Text = "0"; - yObject += 50; + StyleLabel(this.lblVariable, "Değişken:", new Point(445, 16)); + StyleInput(this.txtVariable, "x", new Point(510, 13), new Size(50, 26)); - StyleLabel(this.lblOrder); - this.lblOrder.Location = new System.Drawing.Point(20, yObject); - this.lblOrder.Text = "Order (n):"; - this.numOrder.Location = new System.Drawing.Point(150, yObject); + StyleLabel(this.lblCenterPoint, "Merkez (a):", new Point(575, 16)); + StyleInput(this.txtCenterPoint, "0", new Point(650, 13), new Size(60, 26)); + + StyleLabel(this.lblOrder, "Derece (n):", new Point(14, 56)); + this.numOrder.Location = new Point(110, 53); + this.numOrder.Size = new Size(55, 26); this.numOrder.Minimum = 1; - this.numOrder.Maximum = 20; - this.numOrder.Value = 4; - this.numOrder.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.numOrder.ForeColor = System.Drawing.Color.White; - this.numOrder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - yObject += 60; + this.numOrder.Maximum = 12; + this.numOrder.Value = 5; + this.numOrder.BackColor = Color.FromArgb(15, 23, 42); + this.numOrder.ForeColor = Color.White; - this.btnCalculate.Location = new System.Drawing.Point(150, yObject); - this.btnCalculate.Text = "Calculate Series"; - this.btnCalculate.Size = new System.Drawing.Size(150, 40); - this.btnCalculate.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.btnCalculate.BackColor = System.Drawing.Color.FromArgb(0, 120, 215); - this.btnCalculate.ForeColor = System.Drawing.Color.White; - this.btnCalculate.Font = new System.Drawing.Font("Segoe UI Semibold", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); - this.btnCalculate.FlatAppearance.BorderSize = 0; - yObject += 60; + this.btnCalculate.Location = new Point(180, 50); - StyleLabel(this.lblResult); - this.lblResult.Location = new System.Drawing.Point(20, yObject); - this.lblResult.Text = "Result:"; - this.txtResult.Location = new System.Drawing.Point(150, yObject); - this.txtResult.Size = new System.Drawing.Size(600, 150); + this.pnlInputCard.Controls.Add(this.lblFunction); + this.pnlInputCard.Controls.Add(this.txtFunction); + this.pnlInputCard.Controls.Add(this.lblVariable); + this.pnlInputCard.Controls.Add(this.txtVariable); + this.pnlInputCard.Controls.Add(this.lblCenterPoint); + this.pnlInputCard.Controls.Add(this.txtCenterPoint); + this.pnlInputCard.Controls.Add(this.lblOrder); + this.pnlInputCard.Controls.Add(this.numOrder); + this.pnlInputCard.Controls.Add(this.btnCalculate); + + // Hero Polynomial Card + this.pnlHeroPoly.Location = new Point(24, 150); + this.pnlHeroPoly.Size = new Size(860, 70); + this.pnlHeroPoly.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + this.pnlHeroPoly.BackColor = Color.FromArgb(20, 30, 48); + this.pnlHeroPoly.Padding = new Padding(16, 8, 16, 8); + + this.lblHeroPolyTitle.Text = "HESAPLANAN TAYLOR POLİNOMU"; + this.lblHeroPolyTitle.Location = new Point(14, 8); + this.lblHeroPolyTitle.AutoSize = true; + this.lblHeroPolyTitle.Font = new Font("Segoe UI Semibold", 8F, FontStyle.Bold); + this.lblHeroPolyTitle.ForeColor = Color.FromArgb(148, 163, 184); + + this.lblHeroPolyValue.Text = "P_n(x) = —"; + this.lblHeroPolyValue.Location = new Point(12, 26); + this.lblHeroPolyValue.AutoSize = true; + this.lblHeroPolyValue.Font = new Font("Consolas", 12F, FontStyle.Bold); + this.lblHeroPolyValue.ForeColor = Color.FromArgb(52, 211, 153); + + this.btnCopyPoly.Location = new Point(700, 18); + this.btnCopyPoly.Anchor = AnchorStyles.Top | AnchorStyles.Right; + + this.pnlHeroPoly.Controls.Add(this.lblHeroPolyTitle); + this.pnlHeroPoly.Controls.Add(this.lblHeroPolyValue); + this.pnlHeroPoly.Controls.Add(this.btnCopyPoly); + + // Result + this.lblResult.Text = "📊 Noktadaki Sayısal Türevler ve Terim Katsayıları:"; + this.lblResult.Location = new Point(24, 230); + this.lblResult.AutoSize = true; + this.lblResult.Font = new Font("Segoe UI Semibold", 9.5F, FontStyle.Bold); + this.lblResult.ForeColor = ThemeHelper.LightText; + + this.txtResult.Location = new Point(24, 254); + this.txtResult.Size = new Size(860, 320); + this.txtResult.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + this.txtResult.BackColor = Color.FromArgb(15, 23, 42); + this.txtResult.BorderStyle = BorderStyle.FixedSingle; + this.txtResult.ForeColor = Color.FromArgb(186, 230, 253); this.txtResult.Multiline = true; - this.txtResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.txtResult.Font = new System.Drawing.Font("Consolas", 10F); - this.txtResult.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30))))); - this.txtResult.ForeColor = System.Drawing.Color.White; - this.txtResult.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - - // - // TaylorSeriesControl - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); + this.txtResult.ReadOnly = true; + this.txtResult.ScrollBars = ScrollBars.Vertical; + this.txtResult.Font = new Font("Consolas", 9.5F); + + this.pnlContent.Controls.Add(this.pnlPresets); + this.pnlContent.Controls.Add(this.pnlInputCard); + this.pnlContent.Controls.Add(this.pnlHeroPoly); + this.pnlContent.Controls.Add(this.lblResult); + this.pnlContent.Controls.Add(this.txtResult); + + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.BackColor = ThemeHelper.DarkBackground; this.Controls.Add(this.pnlContent); - this.Controls.Add(this.lblTitle); + this.Controls.Add(this.pnlHeader); this.Name = "TaylorSeriesControl"; - this.Size = new System.Drawing.Size(800, 600); + this.Size = new Size(910, 680); + + this.pnlInputCard.ResumeLayout(false); + this.pnlInputCard.PerformLayout(); + this.pnlHeroPoly.ResumeLayout(false); + this.pnlHeroPoly.PerformLayout(); this.pnlContent.ResumeLayout(false); this.pnlContent.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numOrder)).EndInit(); this.ResumeLayout(false); - } - private System.Windows.Forms.Label lblTitle; - private System.Windows.Forms.Panel pnlContent; - private System.Windows.Forms.Label lblFunction; - private System.Windows.Forms.TextBox txtFunction; - private System.Windows.Forms.Label lblVariable; - private System.Windows.Forms.TextBox txtVariable; - private System.Windows.Forms.Label lblCenterPoint; - private System.Windows.Forms.TextBox txtCenterPoint; - private System.Windows.Forms.Label lblOrder; - private System.Windows.Forms.NumericUpDown numOrder; - private System.Windows.Forms.Button btnCalculate; - private System.Windows.Forms.Label lblResult; - private System.Windows.Forms.TextBox txtResult; + private Panel pnlHeader; + private Panel pnlContent; + private FlowLayoutPanel pnlPresets; + private Label lblPresets; + private Button btnExSin; + private Button btnExExp; + private Button btnExLn; + + private Panel pnlInputCard; + private Label lblFunction; + public TextBox txtFunction; + private Label lblVariable; + public TextBox txtVariable; + private Label lblCenterPoint; + public TextBox txtCenterPoint; + private Label lblOrder; + public NumericUpDown numOrder; + public Button btnCalculate; + + private Panel pnlHeroPoly; + private Label lblHeroPolyTitle; + private Label lblHeroPolyValue; + private Button btnCopyPoly; + + private Label lblResult; + public TextBox txtResult; } } diff --git a/MathApp/MathApp/Controls/TaylorSeriesControl.cs b/MathApp/MathApp/Controls/TaylorSeriesControl.cs index 24d1d02..0b1c2c9 100644 --- a/MathApp/MathApp/Controls/TaylorSeriesControl.cs +++ b/MathApp/MathApp/Controls/TaylorSeriesControl.cs @@ -1,4 +1,7 @@ using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; using System.Windows.Forms; namespace MathApp.Controls @@ -9,27 +12,103 @@ namespace MathApp.Controls { InitializeComponent(); btnCalculate.Click += BtnCalculate_Click; + + btnExSin.Click += (s, e) => LoadPreset("sin(x)", "x", "0", 5); + btnExExp.Click += (s, e) => LoadPreset("exp(x)", "x", "0", 4); + btnExLn.Click += (s, e) => LoadPreset("ln(x)", "x", "1", 4); + + btnCopyPoly.Click += (s, e) => { + if (!string.IsNullOrEmpty(lblHeroPolyValue.Text) && lblHeroPolyValue.Text != "P_n(x) = —") + { + Clipboard.SetText(lblHeroPolyValue.Text); + MessageBox.Show("Taylor polinom açılımı panoya kopyalandı!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + }; + + txtFunction.KeyDown += Input_KeyDown; + txtVariable.KeyDown += Input_KeyDown; + txtCenterPoint.KeyDown += Input_KeyDown; + } + + private void Input_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + e.SuppressKeyPress = true; + BtnCalculate_Click(this, EventArgs.Empty); + } + } + + private void LoadPreset(string fn, string varName, string center, int order) + { + txtFunction.Text = fn; + txtVariable.Text = varName; + txtCenterPoint.Text = center; + numOrder.Value = order; + BtnCalculate_Click(this, EventArgs.Empty); } private void BtnCalculate_Click(object sender, EventArgs e) { try { - string eq = txtFunction.Text; - string variable = txtVariable.Text; - int degree = (int)numOrder.Value; - decimal center = decimal.Parse(txtCenterPoint.Text); + string eq = txtFunction.Text.Trim(); + if (string.IsNullOrWhiteSpace(eq)) + { + txtResult.Text = "Lütfen bir fonksiyon giriniz (Örn: sin(x))."; + lblHeroPolyValue.Text = "Lütfen fonksiyon giriniz."; + lblHeroPolyValue.ForeColor = Color.FromArgb(239, 68, 68); + return; + } - string result = NumericalMethods.Method_TaylorSeries(eq, degree, variable, center); - // Clean up result for display if needed - result = result.Replace("+ -", "- ").Replace("+-", "- "); - - txtResult.Text = "Taylor Series approximation for f(x) =" + Environment.NewLine + - result; + string variable = string.IsNullOrWhiteSpace(txtVariable.Text) ? "x" : txtVariable.Text.Trim(); + int degree = (int)numOrder.Value; + + string centerStr = txtCenterPoint.Text.Trim().Replace(',', '.'); + if (!decimal.TryParse(centerStr, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal center)) + { + txtResult.Text = "❌ Hata: Merkez noktası (a) için geçerli bir sayı giriniz."; + return; + } + + bool prevRad = Function.UseRadians; + Function.UseRadians = true; + string series; + List derivLines = new List(); + try + { + 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++) + { + 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)}"); + } + + series = NumericalMethods.Method_TaylorSeries(eq, degree, variable, center); + } + finally + { + Function.UseRadians = prevRad; + } + + lblHeroPolyValue.Text = $"P_{degree}({variable}) = {series}"; + lblHeroPolyValue.ForeColor = Color.FromArgb(52, 211, 153); + + txtResult.Text = + $"=== {degree}. Dereceden Taylor Polinomu (Merkez a = {center}) ===" + Environment.NewLine + + $"P_{degree}({variable}) = {series}" + Environment.NewLine + Environment.NewLine + + $"=== Noktadaki Sayısal Türevler ve Terim Katsayıları ===" + Environment.NewLine + + string.Join(Environment.NewLine, derivLines); } catch (Exception ex) { - txtResult.Text = "Error: " + ex.Message; + txtResult.Text = "❌ Hata: " + ex.Message; + lblHeroPolyValue.Text = "Hata Oluştu"; + lblHeroPolyValue.ForeColor = Color.FromArgb(239, 68, 68); } } } diff --git a/MathApp/MathApp/Core/DecimalMath.cs b/MathApp/MathApp/Core/DecimalMath.cs index 6c72917..4330fa7 100644 --- a/MathApp/MathApp/Core/DecimalMath.cs +++ b/MathApp/MathApp/Core/DecimalMath.cs @@ -1,26 +1,24 @@ using System; /// -/// Analogy of System.Math class for decimal types +/// Analogy of System.Math class for decimal types with high precision. /// public static class DecimalMath { - /* ... (Content from original file, confirmed no Unity deps) ... */ - /// /// represents PI /// public const decimal PI = 3.14159265358979323846264338327950288419716939937510M; /// - /// represents PI + /// represents machine epsilon for decimal comparisons /// public const decimal Epsilon = 0.0000000000000000001M; /// /// represents 2*PI /// - private const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; + public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; /// /// represents E @@ -30,12 +28,12 @@ public static class DecimalMath /// /// represents PI/2 /// - private const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; + public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; /// /// represents PI/4 /// - private const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; + public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; /// /// represents 1.0/E @@ -68,48 +66,45 @@ public static class DecimalMath private const int MaxIteration = 100; /// - /// Analogy of Math.Exp method + /// Analogy of Math.Exp method with full precision across all ranges /// - /// - /// public static decimal Exp(decimal x) { - var count = 0; - - if (x > One) + if (x == Zero) return One; + if (x > 66.5m) { - count = decimal.ToInt32(decimal.Truncate(x)); - x -= decimal.Truncate(x); + throw new OverflowException("Exp argümanı çok büyük (decimal taşması)."); + } + if (x < -70m) + { + return Zero; } - if (x < Zero) { - count = decimal.ToInt32(decimal.Truncate(x) - 1); - x = One + (x - decimal.Truncate(x)); + return One / Exp(-x); } - var iteration = 1; - var result = One; - var factorial = One; + int count = decimal.ToInt32(decimal.Truncate(x)); + x -= count; + + int iteration = 1; + decimal result = One; + decimal factorial = One; decimal cachedResult; do { cachedResult = result; factorial *= x / iteration++; result += factorial; - } while (cachedResult != result); + } while (cachedResult != result && iteration < MaxIteration); - if (count == 0) - return result; + if (count == 0) return result; return result * PowerN(E, count); } /// /// Analogy of Math.Pow method /// - /// - /// - /// public static decimal Pow(decimal value, decimal pow) { if (pow == Zero) return One; @@ -118,37 +113,32 @@ public static class DecimalMath if (value == Zero) { - if (pow > Zero) - { - return Zero; - } - - throw new Exception("Invalid Operation: zero base and negative power"); + if (pow > Zero) return Zero; + throw new DivideByZeroException("Geçersiz İşlem: Sıfır tabanının negatif kuvveti alınamaz."); } if (pow == -One) return One / value; - var isPowerInteger = IsInteger(pow); + bool isPowerInteger = IsInteger(pow); if (value < Zero && !isPowerInteger) { - throw new Exception("Invalid Operation: negative base and non-integer power"); - } - - if (isPowerInteger && value > Zero) - { - int powerInt = (int)pow; - return PowerN(value, powerInt); - } - - if (isPowerInteger && value < Zero) - { - int powerInt = (int)pow; - if (powerInt % 2 == 0) + // Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5 + decimal invPow = One / pow; + if (IsInteger(invPow)) { - return Exp(pow * Log(-value)); + int q = (int)decimal.Round(invPow); + if (q % 2 != 0) + { + return -Exp(pow * Log(-value)); + } } + throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır."); + } - return -Exp(pow * Log(-value)); + if (isPowerInteger) + { + int powerInt = (int)decimal.Round(pow); + return PowerN(value, powerInt); } return Exp(pow * Log(value)); @@ -156,53 +146,41 @@ public static class DecimalMath private static bool IsInteger(decimal value) { - var longValue = (long)value; - return Abs(value - longValue) <= Epsilon; + var rounded = decimal.Round(value); + return Abs(value - rounded) <= Epsilon; } /// /// Power to the integer value /// - /// - /// - /// public static decimal PowerN(decimal value, int power) { - while (true) + if (power == 0) return One; + if (power < 0) { - if (power == Zero) return One; - if (power < Zero) - { - value = One / value; - power = -power; - continue; - } - - var q = power; - var prod = One; - var current = value; - while (q > 0) - { - if (q % 2 == 1) - { - // detects the 1s in the binary expression of power - prod = current * prod; // picks up the relevant power - q--; - } - - current *= current; // value^i -> value^(2*i) - q >>= 1; - } - - return prod; + value = One / value; + power = -power; } + + int q = power; + decimal prod = One; + decimal current = value; + while (q > 0) + { + if (q % 2 == 1) + { + prod = current * prod; + q--; + } + current *= current; + q >>= 1; + } + return prod; } /// /// Analogy of Math.Log10 /// - /// - /// public static decimal Log10(decimal x) { return Log(x) * Log10Inv; @@ -211,15 +189,13 @@ public static class DecimalMath /// /// Analogy of Math.Log /// - /// - /// public static decimal Log(decimal x) { if (x <= Zero) { - throw new ArgumentException("x must be greater than zero"); + throw new ArgumentException("Logaritma argümanı sıfırdan büyük olmalıdır."); } - var count = 0; + int count = 0; while (x >= One) { x *= Einv; @@ -232,10 +208,11 @@ public static class DecimalMath } x--; if (x == Zero) return count; - var result = Zero; - var iteration = 0; - var y = One; - var cacheResult = result - One; + + decimal result = Zero; + int iteration = 0; + decimal y = One; + decimal cacheResult = result - One; while (cacheResult != result && iteration < MaxIteration) { iteration++; @@ -247,140 +224,127 @@ public static class DecimalMath } /// - /// Analogy of Math.Cos + /// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x) /// - /// - /// - public static decimal Cos(decimal x) + public static decimal Sin(decimal x) { - //truncating to [-2*PI;2*PI] TruncateToPeriodicInterval(ref x); - // now x in (-2pi,2pi) - if (x >= PI && x <= PIx2) - { - return -Cos(x - PI); - } - if (x >= -PIx2 && x <= -PI) - { - return -Cos(x + PI); - } + if (x > PI) x -= PIx2; + else if (x < -PI) x += PIx2; - x *= x; - //y=1-x/2!+x^2/4!-x^3/6!... - var xx = -x * Half; - var y = One + xx; - var cachedY = y - One;//init cache with different value - for (var i = 1; cachedY != y && i < MaxIteration; i++) + if (x > PIdiv2) x = PI - x; + else if (x < -PIdiv2) x = -PI - x; + + decimal x2 = x * x; + decimal term = x; + decimal sum = x; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) { - cachedY = y; - decimal factor = i * ((i << 1) + 3) + 1; //2i^2+2i+i+1=2i^2+3i+1 - factor = -Half / factor; - xx *= x * factor; - y += xx; + cachedSum = sum; + term *= -x2 / ((2 * i) * (2 * i + 1)); + sum += term; + if (sum == cachedSum) break; } - return y; + return sum; + } + + /// + /// Analogy of Math.Cos + /// + public static decimal Cos(decimal x) + { + TruncateToPeriodicInterval(ref x); + + if (x > PI) x -= PIx2; + else if (x < -PI) x += PIx2; + + if (x > PIdiv2) return -Cos(PI - x); + if (x < -PIdiv2) return -Cos(-PI - x); + + decimal x2 = x * x; + decimal term = One; + decimal sum = One; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) + { + cachedSum = sum; + term *= -x2 / ((2 * i - 1) * (2 * i)); + sum += term; + if (sum == cachedSum) break; + } + return sum; } /// /// Analogy of Math.Tan /// - /// - /// public static decimal Tan(decimal x) { - var cos = Cos(x); - if (cos == Zero) throw new ArgumentException(nameof(x)); - //calculate sin using cos - var sin = CalculateSinFromCos(x, cos); - return sin / cos; - } - /// - /// Helper function for calculating sin(x) from cos(x) - /// - /// - /// - /// - private static decimal CalculateSinFromCos(decimal x, decimal cos) - { - var moduleOfSin = Sqrt(One - (cos * cos)); - var sineIsPositive = IsSignOfSinePositive(x); - if (sineIsPositive) return moduleOfSin; - return -moduleOfSin; - } - /// - /// Analogy of Math.Sin - /// - /// - /// - public static decimal Sin(decimal x) - { - var cos = Cos(x); - return CalculateSinFromCos(x, cos); + decimal cos = Cos(x); + if (Abs(cos) <= 1e-25m) throw new ArgumentException("Tan(x) bu noktada tanımsızdır (cos(x) = 0)."); + return Sin(x) / cos; } - - /// - /// Truncates to [-2*PI;2*PI] - /// - /// private static void TruncateToPeriodicInterval(ref decimal x) { - while (x >= PIx2) + if (x >= PIx2 || x <= -PIx2) { - var divide = Math.Abs(decimal.ToInt32(x / PIx2)); - x -= divide * PIx2; + x = x % PIx2; } - - while (x <= -PIx2) - { - var divide = Math.Abs(decimal.ToInt32(x / PIx2)); - x += divide * PIx2; - } - } - - - private static bool IsSignOfSinePositive(decimal x) - { - //truncating to [-2*PI;2*PI] - TruncateToPeriodicInterval(ref x); - - //now x in [-2*PI;2*PI] - if (x >= -PIx2 && x <= -PI) return true; - if (x >= -PI && x <= Zero) return false; - if (x >= Zero && x <= PI) return true; - if (x >= PI && x <= PIx2) return false; - - //will not be reached - throw new ArgumentException(nameof(x)); } /// - /// Analogy of Math.Sqrt + /// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation) /// - /// - /// lasts iteration while error less than this epsilon - /// public static decimal Sqrt(decimal x, decimal epsilon = Zero) { - if (x < Zero) throw new OverflowException("Cannot calculate square root from a negative number"); - //initial approximation - decimal current = (decimal)Math.Sqrt((double)x), previous; - do + if (x < Zero) throw new ArgumentException("Negatif sayının karekökü reel sayılarda alınamaz."); + if (x == Zero) return Zero; + + decimal current = (decimal)Math.Sqrt((double)x); + if (current == Zero) current = x * Half; + + decimal previous = Zero; + int maxSteps = 25; + for (int step = 0; step < maxSteps; step++) { + decimal next = (current + x / current) * Half; + if (next == current || next == previous || Abs(next - current) <= epsilon) + { + return next; + } previous = current; - if (previous == Zero) return Zero; - current = (previous + x / previous) * Half; - } while (Abs(previous - current) > epsilon); + current = next; + } return current; } + /// /// Analogy of Math.Sinh /// - /// - /// public static decimal Sinh(decimal x) { + if (x < Zero) return -Sinh(-x); + + if (Abs(x) < 0.1m) + { + // Taylor series for small x to avoid loss of significance in (e^x - e^-x)/2 + decimal x2 = x * x; + decimal term = x; + decimal sum = x; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) + { + cachedSum = sum; + term *= x2 / ((2 * i) * (2 * i + 1)); + sum += term; + if (sum == cachedSum) break; + } + return sum; + } + var y = Exp(x); var yy = One / y; return (y - yy) * Half; @@ -389,10 +353,9 @@ public static class DecimalMath /// /// Analogy of Math.Cosh /// - /// - /// public static decimal Cosh(decimal x) { + if (x < Zero) x = -x; var y = Exp(x); var yy = One / y; return (y + yy) * Half; @@ -401,8 +364,6 @@ public static class DecimalMath /// /// Analogy of Math.Sign /// - /// - /// public static int Sign(decimal x) { return x < Zero ? -1 : (x > Zero ? 1 : 0); @@ -411,109 +372,103 @@ public static class DecimalMath /// /// Analogy of Math.Tanh /// - /// - /// public static decimal Tanh(decimal x) { - var y = Exp(x); - var yy = One / y; - return (y - yy) / (y + yy); + if (x > 35m) return One; + if (x < -35m) return -One; + + var y = Exp(2m * x); + return (y - One) / (y + One); } /// /// Analogy of Math.Abs /// - /// - /// public static decimal Abs(decimal x) { - if (x <= Zero) - { - return -x; - } - return x; + return x <= Zero ? -x : x; } /// /// Analogy of Math.Asin /// - /// - /// public static decimal Asin(decimal x) { if (x > One || x < -One) { - throw new ArgumentException("x must be in [-1,1]"); + throw new ArgumentException("Asin argümanı [-1, 1] aralığında olmalıdır."); } - //known values if (x == Zero) return Zero; if (x == One) return PIdiv2; - //asin function is odd function + if (x == -One) return -PIdiv2; if (x < Zero) return -Asin(-x); - //my optimize trick here - - // used a math formula to speed up : - // asin(x)=0.5*(pi/2-asin(1-2*x*x)) - // if x>=0 is true - var newX = One - 2 * x * x; - - //for calculating new value near to zero than current - //because we gain more speed with values near to zero if (Abs(x) > Abs(newX)) { var t = Asin(newX); return Half * (PIdiv2 - t); } - var y = Zero; - var result = x; + + decimal y = Zero; + decimal result = x; decimal cachedResult; - var i = 1; + int i = 1; y += result; - var xx = x * x; + decimal xx = x * x; do { cachedResult = result; - result *= xx * (One - Half / (i)); + result *= xx * (One - Half / i); y += result / ((i << 1) + 1); i++; - } while (cachedResult != result); + } while (cachedResult != result && i < MaxIteration); return y; } /// - /// Analogy of Math.Atan + /// Analogy of Math.Atan (safe against overflow for large x) /// - /// - /// public static decimal Atan(decimal x) { if (x == Zero) return Zero; if (x == One) return PIdiv4; + if (x == -One) return -PIdiv4; + + if (x > 100000000000000m) return PIdiv2; + if (x < -100000000000000m) return -PIdiv2; + + if (x > One) + { + return PIdiv2 - Atan(One / x); + } + if (x < -One) + { + return -PIdiv2 - Atan(One / x); + } + return Asin(x / Sqrt(One + x * x)); } + /// /// Analogy of Math.Acos /// - /// - /// public static decimal Acos(decimal x) { + if (x > One || x < -One) + { + throw new ArgumentException("Acos argümanı [-1, 1] aralığında olmalıdır."); + } if (x == Zero) return PIdiv2; if (x == One) return Zero; + if (x == -One) return PI; if (x < Zero) return PI - Acos(-x); return PIdiv2 - Asin(x); } /// /// Analogy of Math.Atan2 - /// for more see this - /// /// - /// - /// - /// public static decimal Atan2(decimal y, decimal x) { if (x > Zero) @@ -536,6 +491,6 @@ public static class DecimalMath { return -PIdiv2; } - throw new ArgumentException("invalid atan2 arguments"); + throw new ArgumentException("Geçersiz Atan2 argümanları (0, 0)."); } } diff --git a/MathApp/MathApp/Core/Function.cs b/MathApp/MathApp/Core/Function.cs index 899dc1d..26d7ff8 100644 --- a/MathApp/MathApp/Core/Function.cs +++ b/MathApp/MathApp/Core/Function.cs @@ -1,71 +1,47 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Globalization; - -/// -/// -/// public enum Type { Variable, Value, UnaryOperator, Operator, Function, Result, Bracket, Comma, Error } + public struct Symbol { public string m_name; public decimal m_value; public Type m_type; + public int m_argCount; public override string ToString() { return m_name; } } -public delegate Symbol EvaluateFunctionDelegate(string name, params Object[] args); + +public delegate Symbol EvaluateFunctionDelegate(string name, params Symbol[] args); + public class Function { - public decimal Result + private static readonly HashSet KnownFunctions = new HashSet(StringComparer.OrdinalIgnoreCase) { - get - { - return m_result; - } - } + "sin", "cos", "tan", "cot", "cosh", "sinh", "tanh", + "log", "ln", "logn", "sqrt", "cbrt", "abs", + "acos", "asin", "atan", "atan2", "exp", + "max", "min", "floor", "ceil", "round", "sign" + }; - public ArrayList Equation - { - get - { - return (ArrayList)m_equation.Clone(); - } - } - public ArrayList Postfix - { - get - { - return (ArrayList)m_postfix.Clone(); - } - } + public static bool UseRadians { get; set; } = true; + + public decimal Result => m_result; + public ArrayList Equation => (ArrayList)m_equation.Clone(); + public ArrayList Postfix => (ArrayList)m_postfix.Clone(); public EvaluateFunctionDelegate DefaultFunctionEvaluation { - set - { - m_defaultFunctionEvaluation = value; - } + set => m_defaultFunctionEvaluation = value; } - public bool Error - { - get - { - return m_bError; - } - } - - public string ErrorDescription - { - get - { - return m_sErrorDescription; - } - } + public bool Error => m_bError; + public string ErrorDescription => m_sErrorDescription; public ArrayList Variables { @@ -96,14 +72,69 @@ public class Function } } + public void SetVariable(string name, decimal value) + { + for (int i = 0; i < m_postfix.Count; i++) + { + Symbol s = (Symbol)m_postfix[i]; + if (s.m_type == Type.Variable && string.Equals(s.m_name, name, StringComparison.OrdinalIgnoreCase)) + { + s.m_value = value; + m_postfix[i] = s; + } + } + } + + public void SetVariables(Dictionary values) + { + for (int i = 0; i < m_postfix.Count; i++) + { + Symbol s = (Symbol)m_postfix[i]; + if (s.m_type == Type.Variable && values.TryGetValue(s.m_name, out decimal val)) + { + s.m_value = val; + m_postfix[i] = s; + } + } + } + public Function() - { } + { + } + + private void AddSymbolWithImplicitMultiplication(Symbol sym) + { + if (m_equation.Count > 0) + { + Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; + bool prevIsOperandOrClose = prev.m_type == Type.Value || + prev.m_type == Type.Variable || + prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}"; + + bool currIsOperandOrOpen = sym.m_type == Type.Value || + sym.m_type == Type.Variable || + sym.m_type == Type.Function || + sym.m_name == "(" || sym.m_name == "[" || sym.m_name == "{"; + + if (prevIsOperandOrClose && currIsOperandOrOpen) + { + Symbol mulSym = new Symbol + { + m_name = "*", + m_value = 0, + m_type = Type.Operator + }; + m_equation.Add(mulSym); + } + } + m_equation.Add(sym); + } public void Parse(string equation) { int state = 1; string temp = ""; - Symbol ctSymbol = new Symbol(); // Initialized to avoid error + Symbol ctSymbol = new Symbol(); m_bError = false; m_sErrorDescription = "None"; @@ -111,179 +142,252 @@ public class Function m_equation.Clear(); m_postfix.Clear(); - int nPos = 0; - //-- Remove all white spaces from the equation string -- - equation = equation.Trim(); - while ((nPos = equation.IndexOf(' ')) != -1) - equation = equation.Remove(nPos, 1); + if (string.IsNullOrWhiteSpace(equation)) + { + m_bError = true; + m_sErrorDescription = "Denklem boş olamaz."; + return; + } + // We process whitespace as delimiter without deleting it globally for (int i = 0; i < equation.Length; i++) { + char ch = equation[i]; switch (state) { - case 1: - if (Char.IsNumber(equation[i])) + case 1: // Neutral + if (char.IsWhiteSpace(ch)) + { + continue; + } + if (char.IsDigit(ch) || ch == '.') { state = 2; - temp += equation[i]; + temp += ch; } - else if (Char.IsLetter(equation[i])) + else if (char.IsLetter(ch)) { state = 3; - temp += equation[i]; + temp += ch; } else { - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) - { - case ",": - case ".": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; - break; - } - m_equation.Add(ctSymbol); + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } break; - case 2: - if ((Char.IsNumber(equation[i])) || (equation[i] == '.') || (equation[i] == ',')) - temp += equation[i]; - else if (!Char.IsLetter(equation[i])) + + case 2: // Reading Number + if (char.IsDigit(ch) || ch == '.') { - state = 1; - ctSymbol.m_name = temp; - ctSymbol.m_value = Decimal.Parse(temp, System.Globalization.CultureInfo.InvariantCulture); - ctSymbol.m_type = Type.Value; - m_equation.Add(ctSymbol); - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) - { - case ",": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; - break; - } - m_equation.Add(ctSymbol); + temp += ch; + } + else if (char.IsWhiteSpace(ch)) + { + if (!EmitNumberSymbol(temp)) return; temp = ""; + state = 1; } - break; - case 3: - if (Char.IsLetterOrDigit(equation[i])) - temp += equation[i]; else { - state = 1; - ctSymbol.m_name = temp; - ctSymbol.m_value = 0; - if (equation[i] == '(') - ctSymbol.m_type = Type.Function; + if (!EmitNumberSymbol(temp)) return; + temp = ""; + + if (char.IsLetter(ch)) + { + state = 3; + temp += ch; + } else { - if (ctSymbol.m_name == "pi") - ctSymbol.m_value = DecimalMath.PI; - else if (ctSymbol.m_name == "e") - ctSymbol.m_value = DecimalMath.E; - ctSymbol.m_type = Type.Variable; + state = 1; + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } - m_equation.Add(ctSymbol); - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) + } + break; + + case 3: // Reading Identifier + if (char.IsLetterOrDigit(ch)) + { + temp += ch; + } + else if (char.IsWhiteSpace(ch)) + { + // Lookahead to see if next non-whitespace is '(' + bool nextIsOpen = false; + for (int k = i + 1; k < equation.Length; k++) { - case ",": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; + if (!char.IsWhiteSpace(equation[k])) + { + nextIsOpen = (equation[k] == '(' || equation[k] == '[' || equation[k] == '{'); break; + } } - m_equation.Add(ctSymbol); + EmitIdentifierSymbol(temp, nextIsOpen); temp = ""; + state = 1; + } + else + { + state = 1; + EmitIdentifierSymbol(temp, ch == '(' || ch == '[' || ch == '{'); + temp = ""; + + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } break; } } + if (temp != "") { - ctSymbol.m_name = temp; if (state == 2) { - ctSymbol.m_value = Decimal.Parse(temp, System.Globalization.CultureInfo.InvariantCulture); - ctSymbol.m_type = Type.Value; + if (!EmitNumberSymbol(temp)) return; } else { - if (ctSymbol.m_name == "pi") - ctSymbol.m_value = DecimalMath.PI; - else if (ctSymbol.m_name == "e") - ctSymbol.m_value = DecimalMath.E; - else - ctSymbol.m_value = 0; - ctSymbol.m_type = Type.Variable; + EmitIdentifierSymbol(temp, false); } - m_equation.Add(ctSymbol); } } + private bool EmitNumberSymbol(string temp) + { + if (!decimal.TryParse(temp, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) + { + m_bError = true; + m_sErrorDescription = "Geçersiz sayı formatı: " + temp; + return false; + } + + Symbol sym = new Symbol + { + m_name = temp, + m_value = val, + m_type = Type.Value + }; + AddSymbolWithImplicitMultiplication(sym); + return true; + } + + private void EmitIdentifierSymbol(string temp, bool isNextOpenParen) + { + Symbol sym = new Symbol + { + m_name = temp, + m_value = 0 + }; + + string lower = temp.ToLowerInvariant(); + if (lower == "pi") + { + sym.m_value = DecimalMath.PI; + sym.m_type = Type.Value; + } + else if (lower == "e") + { + sym.m_value = DecimalMath.E; + sym.m_type = Type.Value; + } + else if (isNextOpenParen) + { + if (temp.Length == 1 && (temp == "x" || temp == "y" || temp == "z" || temp == "t" || temp == "u" || temp == "v")) + { + sym.m_type = Type.Variable; + } + else + { + sym.m_type = Type.Function; + } + } + else + { + sym.m_type = Type.Variable; + } + AddSymbolWithImplicitMultiplication(sym); + } + + private Symbol ClassifyNonAlphanumeric(string token) + { + Symbol ctSymbol = new Symbol + { + m_name = token, + m_value = 0 + }; + + switch (token) + { + case ",": + case ";": + ctSymbol.m_type = Type.Comma; + break; + case "(": + case ")": + case "[": + case "]": + case "{": + case "}": + ctSymbol.m_type = Type.Bracket; + break; + default: + if (m_equation.Count == 0) + { + ctSymbol.m_type = Type.UnaryOperator; + } + else + { + Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; + if (prev.m_type == Type.Value || prev.m_type == Type.Variable || + prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}") + { + ctSymbol.m_type = Type.Operator; + } + else + { + ctSymbol.m_type = Type.UnaryOperator; + } + } + break; + } + return ctSymbol; + } + public void Infix2Postfix() { + m_postfix.Clear(); Symbol tpSym; Stack tpStack = new Stack(); + Stack fnArgCounts = new Stack(); + foreach (Symbol sym in m_equation) { if ((sym.m_type == Type.Value) || (sym.m_type == Type.Variable)) m_postfix.Add(sym); + else if (sym.m_type == Type.Function) + { + tpStack.Push(sym); + fnArgCounts.Push(1); + } else if ((sym.m_name == "(") || (sym.m_name == "[") || (sym.m_name == "{")) tpStack.Push(sym); + else if (sym.m_type == Type.Comma) + { + while (tpStack.Count > 0) + { + tpSym = (Symbol)tpStack.Peek(); + if (tpSym.m_name == "(" || tpSym.m_name == "[" || tpSym.m_name == "{") + break; + m_postfix.Add(tpStack.Pop()); + } + if (fnArgCounts.Count > 0) + { + int c = fnArgCounts.Pop(); + fnArgCounts.Push(c + 1); + } + } else if ((sym.m_name == ")") || (sym.m_name == "]") || (sym.m_name == "}")) { if (tpStack.Count > 0) @@ -292,28 +396,56 @@ public class Function while ((tpSym.m_name != "(") && (tpSym.m_name != "[") && (tpSym.m_name != "{")) { m_postfix.Add(tpSym); + if (tpStack.Count == 0) break; tpSym = (Symbol)tpStack.Pop(); } + + if (tpStack.Count > 0 && ((Symbol)tpStack.Peek()).m_type == Type.Function) + { + Symbol fn = (Symbol)tpStack.Pop(); + fn.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; + m_postfix.Add(fn); + } } } else if (sym.m_type == Type.UnaryOperator) { + // Unary operators (like unary - or +) modify the operand to their right. + // They should never pop binary operators (^, *, /, +, -) from the stack. + tpStack.Push(sym); + } + else if (sym.m_name == "^") + { + // Right-associative operator ^ + while (tpStack.Count > 0) + { + tpSym = (Symbol)tpStack.Peek(); + if ((tpSym.m_type == Type.Operator || tpSym.m_type == Type.Function) && + Precedence(tpSym) > Precedence(sym)) + { + m_postfix.Add(tpStack.Pop()); + } + else + { + break; + } + } tpStack.Push(sym); } else { - if (tpStack.Count > 0) + while (tpStack.Count > 0) { - tpSym = (Symbol)tpStack.Pop(); - while ((tpStack.Count != 0) && ((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym))) + tpSym = (Symbol)tpStack.Peek(); + if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function)) && + (Precedence(tpSym) >= Precedence(sym))) { - m_postfix.Add(tpSym); - tpSym = (Symbol)tpStack.Pop(); + m_postfix.Add(tpStack.Pop()); } - if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym))) - m_postfix.Add(tpSym); else - tpStack.Push(tpSym); + { + break; + } } tpStack.Push(sym); } @@ -321,6 +453,10 @@ public class Function while (tpStack.Count > 0) { tpSym = (Symbol)tpStack.Pop(); + if (tpSym.m_type == Type.Function && tpSym.m_argCount == 0) + { + tpSym.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; + } m_postfix.Add(tpSym); } } @@ -329,7 +465,6 @@ public class Function { Symbol tpSym1, tpSym2, tpResult; Stack tpStack = new Stack(); - ArrayList fnParam = new ArrayList(); m_bError = false; foreach (Symbol sym in m_postfix) { @@ -337,6 +472,12 @@ public class Function tpStack.Push(sym); else if (sym.m_type == Type.UnaryOperator) { + if (tpStack.Count < 1) + { + m_bError = true; + m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; + return; + } tpSym1 = (Symbol)tpStack.Pop(); tpResult = Evaluate(sym, tpSym1); if (tpResult.m_type == Type.Error) @@ -349,6 +490,12 @@ public class Function } else if (sym.m_type == Type.Operator) { + if (tpStack.Count < 2) + { + m_bError = true; + m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; + return; + } tpSym1 = (Symbol)tpStack.Pop(); tpSym2 = (Symbol)tpStack.Pop(); tpResult = Evaluate(tpSym2, sym, tpSym1); @@ -360,55 +507,30 @@ public class Function } tpStack.Push(tpResult); } - else if (sym.m_type == Type.Comma) - { - tpStack.Push(sym); - } else if (sym.m_type == Type.Function) { - fnParam.Clear(); - tpSym1 = (Symbol)tpStack.Pop(); - if ((tpSym1.m_type == Type.Value) || (tpSym1.m_type == Type.Variable) || (tpSym1.m_type == Type.Result)) + int count = sym.m_argCount > 0 ? sym.m_argCount : 1; + if (tpStack.Count < count) { - tpResult = EvaluateFunction(sym.m_name, tpSym1); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + m_bError = true; + m_sErrorDescription = $"Fonksiyon '{sym.m_name}' için argüman eksik."; + return; } - else if (tpSym1.m_type == Type.Comma) + + Symbol[] fnParam = new Symbol[count]; + for (int i = count - 1; i >= 0; i--) { - while (tpSym1.m_type == Type.Comma) - { - tpSym1 = (Symbol)tpStack.Pop(); - fnParam.Add(tpSym1); - tpSym1 = (Symbol)tpStack.Pop(); - } - fnParam.Add(tpSym1); - tpResult = EvaluateFunction(sym.m_name, fnParam.ToArray()); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + fnParam[i] = (Symbol)tpStack.Pop(); } - else + + tpResult = EvaluateFunction(sym.m_name, fnParam); + if (tpResult.m_type == Type.Error) { - tpStack.Push(tpSym1); - tpResult = EvaluateFunction(sym.m_name); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + m_bError = true; + m_sErrorDescription = tpResult.m_name; + return; } + tpStack.Push(tpResult); } } if (tpStack.Count == 1) @@ -416,6 +538,11 @@ public class Function tpResult = (Symbol)tpStack.Pop(); m_result = tpResult.m_value; } + else if (tpStack.Count > 1) + { + m_bError = true; + m_sErrorDescription = "İfade tam çözümlenemedi (fazla terim)."; + } } protected int Precedence(Symbol sym) @@ -425,16 +552,16 @@ public class Function case Type.Bracket: return 7; case Type.Function: - return 5; + return 6; case Type.UnaryOperator: - return 4; + return 3; case Type.Comma: return 0; } switch (sym.m_name) { case "^": - return 3; + return 5; case "/": case "*": case "%": @@ -448,21 +575,21 @@ public class Function protected Symbol Evaluate(Symbol opr, Symbol sym1) { - Symbol result; + Symbol result = default; result.m_name = opr.m_name + sym1.m_name; result.m_type = Type.Result; result.m_value = 0; switch (opr.m_name) { case "+": - result.m_value = sym1.m_value; ; + result.m_value = sym1.m_value; break; case "-": result.m_value = -1 * sym1.m_value; break; default: result.m_type = Type.Error; - result.m_name = "Undefine unary operator: " + opr.m_name + "."; + result.m_name = "Tanımsız tekli operatör: " + opr.m_name; break; } return result; @@ -470,244 +597,390 @@ public class Function protected Symbol Evaluate(Symbol sym1, Symbol opr, Symbol sym2) { - Symbol result; + Symbol result = default; result.m_name = sym1.m_name + opr.m_name + sym2.m_name; result.m_type = Type.Result; result.m_value = 0; - switch (opr.m_name) + try { - case "^": - result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); - break; - case "/": - { + switch (opr.m_name) + { + case "^": + result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); + break; + case "/": if (sym2.m_value != 0) result.m_value = sym1.m_value / sym2.m_value; else { - result.m_name = "Divide by Zero."; + result.m_name = "Sıfıra bölme hatası (Divide by Zero)."; result.m_type = Type.Error; } break; - } - case "*": - result.m_value = sym1.m_value * sym2.m_value; - break; - case "%": - result.m_value = sym1.m_value % sym2.m_value; - break; - case "+": - result.m_value = sym1.m_value + sym2.m_value; - break; - case "-": - result.m_value = sym1.m_value - sym2.m_value; - break; - default: - result.m_type = Type.Error; - result.m_name = "Undefine operator: " + opr.m_name + "."; - break; + case "*": + result.m_value = sym1.m_value * sym2.m_value; + break; + case "%": + if (sym2.m_value != 0) + result.m_value = sym1.m_value % sym2.m_value; + else + { + result.m_name = "Sıfıra göre mod alınamaz."; + result.m_type = Type.Error; + } + break; + case "+": + result.m_value = sym1.m_value + sym2.m_value; + break; + case "-": + result.m_value = sym1.m_value - sym2.m_value; + break; + default: + result.m_type = Type.Error; + result.m_name = "Tanımsız operatör: " + opr.m_name; + break; + } + } + catch (Exception ex) + { + result.m_type = Type.Error; + result.m_name = ex.Message; } return result; } - protected Symbol EvaluateFunction(string name, params Object[] args) + protected Symbol EvaluateFunction(string name, params Symbol[] args) { - Symbol result; + Symbol result = default; result.m_name = ""; result.m_type = Type.Result; result.m_value = 0; - switch (name) + + string lowerName = name.ToLowerInvariant(); + decimal angleFactor = UseRadians ? 1.0m : (DecimalMath.PI / 180.0m); + decimal invAngleFactor = UseRadians ? 1.0m : (180.0m / DecimalMath.PI); + + try { - case "cos": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Cos(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sin": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sin(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "tan": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Tan(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "cosh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Cosh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sinh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sinh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "tanh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Tanh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "log": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log10(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "ln": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "logn": - if (args.Length == 2) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + "'" + ((Symbol)args[1]).m_value.ToString() + ")"; - // log_b(x) = ln(x) / ln(b) - result.m_value = DecimalMath.Log(((Symbol)args[0]).m_value) / DecimalMath.Log(((Symbol)args[1]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sqrt": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sqrt(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "abs": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Abs(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "acos": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Acos(((Symbol)args[0]).m_value) * 180 / DecimalMath.PI; - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "asin": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Asin(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "atan": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Atan(((Symbol)args[0]).m_value) * 180 / DecimalMath.PI; - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "exp": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Exp(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - default: - if (m_defaultFunctionEvaluation != null) - result = m_defaultFunctionEvaluation(name, args); - else - { - result.m_name = "Function: " + name + ", not found."; - result.m_type = Type.Error; - } - break; + switch (lowerName) + { + case "cos": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Cos(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sin": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sin(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "tan": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Tan(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cot": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + decimal sinVal = DecimalMath.Sin(v * angleFactor); + if (DecimalMath.Abs(sinVal) <= 1e-25m) + { + result.m_name = "Cot(x) bu noktada tanımsızdır (sin(x) = 0)."; + result.m_type = Type.Error; + } + else + { + result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal; + } + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cosh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Cosh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sinh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sinh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "tanh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Tanh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "log": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log10(v); + } + else if (args.Length == 2) + { + decimal v = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "ln": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "logn": + if (args.Length == 2) + { + decimal v = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sqrt": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sqrt(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cbrt": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = v < 0 ? -DecimalMath.Pow(-v, 1m / 3m) : DecimalMath.Pow(v, 1m / 3m); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "abs": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Abs(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "acos": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Acos(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "asin": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Asin(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "atan": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Atan(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "atan2": + if (args.Length == 2) + { + decimal y = ((Symbol)args[0]).m_value; + decimal x = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + y.ToString(CultureInfo.InvariantCulture) + "," + x.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Atan2(y, x) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: atan2(y, x)"; + result.m_type = Type.Error; + } + break; + case "exp": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Exp(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "max": + if (args.Length == 2) + { + decimal a = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_value = Math.Max(a, b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: max(a, b)"; + result.m_type = Type.Error; + } + break; + case "min": + if (args.Length == 2) + { + decimal a = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_value = Math.Min(a, b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: min(a, b)"; + result.m_type = Type.Error; + } + break; + case "floor": + if (args.Length == 1) + { + result.m_value = decimal.Floor(((Symbol)args[0]).m_value); + } + break; + case "ceil": + if (args.Length == 1) + { + result.m_value = decimal.Ceiling(((Symbol)args[0]).m_value); + } + break; + case "round": + if (args.Length == 1) + { + result.m_value = decimal.Round(((Symbol)args[0]).m_value); + } + break; + case "sign": + if (args.Length == 1) + { + result.m_value = DecimalMath.Sign(((Symbol)args[0]).m_value); + } + break; + default: + if (m_defaultFunctionEvaluation != null) + result = m_defaultFunctionEvaluation(name, args); + else + { + result.m_name = "Fonksiyon bulunamadı: " + name; + result.m_type = Type.Error; + } + break; + } + } + catch (Exception ex) + { + result.m_name = ex.Message; + result.m_type = Type.Error; } return result; } diff --git a/MathApp/MathApp/Core/Matrix.cs b/MathApp/MathApp/Core/Matrix.cs index ff51221..ab84f5e 100644 --- a/MathApp/MathApp/Core/Matrix.cs +++ b/MathApp/MathApp/Core/Matrix.cs @@ -2,6 +2,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; +using DotNetMatrix; public class Matrix { @@ -15,7 +16,6 @@ public class Matrix res[i] = new decimal[columns]; for (int j = 0; j < columns; j++) { - // Replaced UnityEngine.Random with System.Random double range = (double)(max - min); double sample = random.NextDouble(); double scaled = (sample * range) + (double)min; @@ -28,6 +28,7 @@ public class Matrix public static decimal[][] Transpoze(decimal[][] _m) { + if (_m == null || _m.Length == 0) return new decimal[0][]; decimal[][] res = new decimal[_m[0].Length][]; for (int i = 0; i < _m[0].Length; i++) { @@ -45,183 +46,73 @@ public class Matrix public static decimal MatrixDeterminant(decimal[][] _m) { - if (_m.Length == _m[0].Length) + if (_m == null || _m.Length == 0) return 0; + if (_m.Length != _m[0].Length) { - int c = _m.Length; - if (c == 2) - { - return (decimal)Math.Round(_m[0][0] * _m[1][1] - _m[0][1] * _m[1][0], 5); - } - else if (c == 1) - { - return (decimal)Math.Round(_m[0][0], 5); - } - else if (c == 0) - { - Console.WriteLine("Matrix is empty!"); - return 0; - } - else - { - decimal resDet = 0; - for (int i = 0; i < c; i++) - { - for (int j = 0; j < c; j++) - { - decimal[][] newM = new decimal[c - 1][]; - for (int k = 0; k < c - 1; k++) - { - newM[k] = new decimal[c - 1]; - } - - bool isAddedK = false, isAddedL = false; - int offsetK = 0, offsetL = 0; - - for (int k = 0; k < c; k++) - { - isAddedL = false; - offsetL = 0; - for (int l = 0; l < c; l++) - { - if (!(k == i || l == j)) - { - newM[k + offsetK][l + offsetL] = _m[k][l]; - } - else - { - if (!isAddedK && k == i) - { - offsetK = -1; - isAddedK = true; - } - if (!isAddedL && l == j) - { - offsetL = -1; - isAddedL = true; - } - } - } - } - - decimal cofactor = (decimal)Math.Pow(-1, 0 + j + 2) * MatrixDeterminant(newM); - resDet += cofactor * _m[0][j]; - } - } - return (decimal)Math.Round(resDet, 5); - } - } - else - { - Console.WriteLine("This matrix is not a square matrix!"); - return 0; + throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır."); } + + int n = _m.Length; + if (n == 1) return _m[0][0]; + if (n == 2) return _m[0][0] * _m[1][1] - _m[0][1] * _m[1][0]; + + // Use O(n^3) LU Decomposition instead of O(n!) recursive Laplace expansion + GeneralMatrix gm = GeneralMatrix.ConstructWithCopy(_m); + return gm.Determinant(); } public static decimal[] SolveEquation(decimal[][] _m, decimal[] _v) { + if (_m == null || _v == null || _m.Length == 0) return new decimal[0]; int len = _m.Length; - decimal[] res = new decimal[len]; - decimal d0 = MatrixDeterminant(_m); - + GeneralMatrix A = GeneralMatrix.ConstructWithCopy(_m); + GeneralMatrix b = new GeneralMatrix(len, 1); for (int i = 0; i < len; i++) { - decimal[][] testMa = new decimal[len][]; - for (int j = 0; j < len; j++) - { - testMa[j] = new decimal[len]; - for (int k = 0; k < len; k++) - { - testMa[j][k] = _m[j][k]; - } - } - for (int j = 0; j < len; j++) - { - testMa[j][i] = _v[j]; - } - decimal di = MatrixDeterminant(testMa); - res[i] = (decimal)Math.Round(di / d0, 5); + b.Array[i][0] = _v[i]; } + GeneralMatrix x = A.Solve(b); + decimal[] res = new decimal[len]; + for (int i = 0; i < len; i++) + { + res[i] = x.Array[i][0]; + } return res; } public static decimal[][] ConvertLinearEquationsToMatrix(List equations, List variables) { - if (equations.Count != variables.Count) return null; + if (equations == null || variables == null || equations.Count != variables.Count) return null; - decimal[][] res = new decimal[equations.Count][]; - for (int i = 0; i < equations.Count; i++) + int n = equations.Count; + decimal[][] res = new decimal[n][]; + for (int i = 0; i < n; i++) { - res[i] = new decimal[equations.Count]; - string eq = equations[i].Replace(" ", ""); // Remove spaces + res[i] = new decimal[n]; + string eq = equations[i]; + if (eq.Contains("=")) + { + string[] parts = eq.Split('='); + eq = parts[0] + "-(" + parts[1] + ")"; + } - // Split by operators but keep them? - // Better approach: Go through each variable and find its coefficient in the string - - for (int k = 0; k < variables.Count; k++) + // Use numerical evaluation to extract exact linear coefficients reliably: + // f(0, 0, ...) = c + // f(0, ..., x_k=1, ..., 0) - c = coeff_k + Dictionary zeroPts = new Dictionary(); + foreach (string v in variables) zeroPts[v] = 0m; + + decimal f0 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); + + for (int k = 0; k < n; k++) { string varName = variables[k]; - // Find all occurrences? A variable should appear once per equation linearly. - // We need to look for "...[coeff]varName..." - // Simple parser: Scan the equation string. - - // Let's use a robust approach: Replace all other variables with 0 and evaluate? - // No, that requires an expression evaluator. - - // String manipulation approach (as per original code intent but fixed): - int varIndex = eq.IndexOf(varName); - if (varIndex != -1) - { - // Find coefficient ending at varIndex - 1 - string coeffStr = ""; - int curr = varIndex - 1; - - // Scan backwards to find numbers or sign - while (curr >= 0) - { - char c = eq[curr]; - if (char.IsDigit(c) || c == '.') - { - coeffStr = c + coeffStr; - curr--; - } - else if (c == '+' || c == '-') - { - coeffStr = c + coeffStr; - break; // Sign is the start of the coefficient - } - else - { - break; // Another char (maybe another variable?) - } - } - - if (string.IsNullOrEmpty(coeffStr) || coeffStr == "+") - { - res[i][k] = 1; - } - else if (coeffStr == "-") - { - res[i][k] = -1; - } - else - { - if (decimal.TryParse(coeffStr, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) - { - res[i][k] = val; - } - else - { - // Parse error fallback - res[i][k] = 1; - } - } - } - else - { - res[i][k] = 0; - } + zeroPts[varName] = 1m; + decimal f1 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); + res[i][k] = f1 - f0; + zeroPts[varName] = 0m; } } return res; @@ -229,6 +120,7 @@ public class Matrix public static decimal[][] MatrixMultiplication(decimal[][] _m1, decimal[][] _m2) { + if (_m1 == null || _m2 == null || _m1.Length == 0 || _m2.Length == 0) return null; if (_m1[0].Length == _m2.Length) { decimal[][] res = new decimal[_m1.Length][]; @@ -253,18 +145,20 @@ public class Matrix } else { - Console.WriteLine("Matrices cannot be multiplied!"); - return null; + throw new ArgumentException("Birinci matrisin sütun sayısı ile ikinci matrisin satır sayısı eşit olmalıdır."); } } + public static decimal[][] MatrixMultiplication(decimal[][] _m, decimal _c) { - decimal[][] res = _m; + if (_m == null) return null; + decimal[][] res = new decimal[_m.Length][]; for (int i = 0; i < _m.Length; i++) { - for (int j = 0; j < _m[0].Length; j++) + res[i] = new decimal[_m[i].Length]; + for (int j = 0; j < _m[i].Length; j++) { - res[i][j] *= _c; + res[i][j] = _m[i][j] * _c; } } return res; @@ -272,47 +166,42 @@ public class Matrix public static decimal[] TurnListToVector(List _vec) { - decimal[] res = new decimal[_vec.Count]; - for (int i = 0; i < _vec.Count; i++) - { - res[i] = _vec[i]; - } - return res; + return _vec.ToArray(); } + public static decimal[][] TurnListToMatrix(List> _m) { decimal[][] res = new decimal[_m.Count][]; for (int i = 0; i < _m.Count; i++) { - res[i] = new decimal[_m[i].Count]; - for (int j = 0; j < _m[i].Count; j++) - { - res[i][j] = _m[i][j]; - } + res[i] = _m[i].ToArray(); } return res; } - public static string DebugMatrix(decimal[][] _m, string _sep = " ") + public static string DebugMatrix(decimal[][] _m, string _sep = "\t") { - string sum = ""; + if (_m == null || _m.Length == 0) return ""; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < _m.Length; i++) { - for (int j = 0; j < _m[0].Length; j++) + for (int j = 0; j < _m[i].Length; j++) { - sum += _m[i][j] + ((j == _m[0].Length - 1) ? "\n" : _sep); + sb.Append(_m[i][j].ToString("0.######", CultureInfo.InvariantCulture)); + sb.Append(j == _m[i].Length - 1 ? Environment.NewLine : _sep); } } - return sum; - } - public static string DebugVector(decimal[] _v, string _sep = " ") - { - string sum = ""; - for (int i = 0; i < _v.Length; i++) - { - sum += _v[i] + "\n"; - } - return sum; + return sb.ToString(); } + public static string DebugVector(decimal[] _v, string _sep = " ") + { + if (_v == null) return ""; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + for (int i = 0; i < _v.Length; i++) + { + sb.AppendLine(_v[i].ToString("0.######", CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } } diff --git a/MathApp/MathApp/Core/Matrix/CholeskyDecomposition.cs b/MathApp/MathApp/Core/Matrix/CholeskyDecomposition.cs index 2f13915..d185d19 100644 --- a/MathApp/MathApp/Core/Matrix/CholeskyDecomposition.cs +++ b/MathApp/MathApp/Core/Matrix/CholeskyDecomposition.cs @@ -56,6 +56,7 @@ namespace DotNetMatrix // Main loop. for (int j = 0; j < n; j++) { + if (!isspd) break; decimal[] Lrowj = L[j]; decimal d = 0.0m; for (int k = 0; k < j; k++) @@ -66,13 +67,25 @@ namespace DotNetMatrix { s += Lrowk[i] * Lrowj[i]; } + if (L[k][k] <= 0.0m) + { + isspd = false; + break; + } Lrowj[k] = s = (A[j][k] - s) / L[k][k]; d = d + s * s; isspd = isspd & (A[k][j] == A[j][k]); } + if (!isspd) break; d = A[j][j] - d; isspd = isspd & (d > 0.0m); - L[j][j] = (decimal)Math.Sqrt(Math.Max((double)d, 0)); + if (!isspd || d <= 0.0m) + { + isspd = false; + L[j][j] = 0.0m; + break; + } + L[j][j] = DecimalMath.Sqrt(d); for (int k = j + 1; k < n; k++) { L[j][k] = 0.0m; diff --git a/MathApp/MathApp/Core/Matrix/EigenvalueDecomposition.cs b/MathApp/MathApp/Core/Matrix/EigenvalueDecomposition.cs index 9a8a49b..3cf03a8 100644 --- a/MathApp/MathApp/Core/Matrix/EigenvalueDecomposition.cs +++ b/MathApp/MathApp/Core/Matrix/EigenvalueDecomposition.cs @@ -146,7 +146,7 @@ namespace DotNetMatrix decimal f = 0.0m; decimal tst1 = 0.0m; - decimal eps = (decimal)DecimalMath.Pow(2.0m, - 52.0m); + decimal eps = DecimalMath.Pow(2.0m, -64.0m); for (int l = 0; l < n; l++) { tst1 = System.Math.Max(tst1, System.Math.Abs(d[l]) + System.Math.Abs(e[l])); @@ -166,6 +166,7 @@ namespace DotNetMatrix do { iter = iter + 1; + if (iter > 120) break; decimal g = d[l]; decimal p = (d[l + 1] - g) / (2.0m * e[l]); decimal r = Maths.Hypot(p, 1.0m); @@ -388,8 +389,10 @@ namespace DotNetMatrix } int iter = 0; - while (n >= low) + int totalIter = 0; + while (n >= low && totalIter < 400) { + totalIter++; int l = n; while (l > low) { @@ -702,7 +705,7 @@ namespace DotNetMatrix } t = System.Math.Abs(H[i][n]); - if ((eps * t) * t > 1) + if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) { for (int j = i; j <= n; j++) { @@ -782,7 +785,7 @@ namespace DotNetMatrix } t = System.Math.Max(System.Math.Abs(H[i][n - 1]), System.Math.Abs(H[i][n])); - if ((eps * t) * t > 1) + if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) { for (int j = i; j <= n; j++) { diff --git a/MathApp/MathApp/Core/Matrix/SingularValueDecomposition.cs b/MathApp/MathApp/Core/Matrix/SingularValueDecomposition.cs index 3a51b8e..206d5f6 100644 --- a/MathApp/MathApp/Core/Matrix/SingularValueDecomposition.cs +++ b/MathApp/MathApp/Core/Matrix/SingularValueDecomposition.cs @@ -12,9 +12,19 @@ namespace DotNetMatrix public SingularValueDecomposition(GeneralMatrix Arg) { - decimal[][] A = Arg.ArrayCopy; m = Arg.RowDimension; n = Arg.ColumnDimension; + + if (m < n) + { + SingularValueDecomposition svdTrans = new SingularValueDecomposition(Arg.Transpose()); + s = (decimal[])svdTrans.s.Clone(); + U = svdTrans.V; + V = svdTrans.U; + return; + } + + decimal[][] A = Arg.ArrayCopy; int nu = System.Math.Min(m, n); s = new decimal[System.Math.Min(m + 1, n)]; U = new decimal[m][]; @@ -226,8 +236,8 @@ namespace DotNetMatrix int pp = p - 1; int iter = 0; - decimal eps = (decimal)Math.Pow(2.0f, - 52.0f); - while (p > 0) + decimal eps = DecimalMath.Pow(2.0m, -64.0m); + while (p > 0 && iter < 150) { int k, kase; for (k = p - 2; k >= - 1; k--) @@ -456,11 +466,12 @@ namespace DotNetMatrix { get { - GeneralMatrix X = new GeneralMatrix(n, n); + int nu = System.Math.Min(m, n); + GeneralMatrix X = new GeneralMatrix(nu, nu); decimal[][] S = X.Array; - for (int i = 0; i < n; i++) + for (int i = 0; i < nu; i++) { - for (int j = 0; j < n; j++) + for (int j = 0; j < nu; j++) { S[i][j] = 0.0m; } @@ -472,12 +483,12 @@ namespace DotNetMatrix public virtual GeneralMatrix GetU() { - return new GeneralMatrix(U, m, System.Math.Min(m + 1, n)); + return new GeneralMatrix(U, m, System.Math.Min(m, n)); } public virtual GeneralMatrix GetV() { - return new GeneralMatrix(V, n, n); + return new GeneralMatrix(V, n, System.Math.Min(m, n)); } public virtual decimal Norm2() @@ -487,7 +498,8 @@ namespace DotNetMatrix public virtual decimal Condition() { - return s[0] / s[System.Math.Min(m, n) - 1]; + decimal minS = s[System.Math.Min(m, n) - 1]; + return minS != 0m ? s[0] / minS : decimal.MaxValue; } public virtual int Rank() diff --git a/MathApp/MathApp/Core/NumericalMethods.cs b/MathApp/MathApp/Core/NumericalMethods.cs index 6d0677b..ec2bacd 100644 --- a/MathApp/MathApp/Core/NumericalMethods.cs +++ b/MathApp/MathApp/Core/NumericalMethods.cs @@ -1,232 +1,440 @@ using DotNetMatrix; +using System; using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; -using System.Text; using System.Linq; -using System; +using System.Text; +using System.Text.RegularExpressions; public class NumericalMethods { - // --- Original Methods Ported --- + public static string NormalizeEquation(string eq) + { + if (string.IsNullOrWhiteSpace(eq)) return ""; + eq = eq.Trim(); + if (eq.Contains("=")) + { + string[] parts = eq.Split('='); + if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[1])) + { + return "(" + parts[0] + ")-(" + parts[1] + ")"; + } + } + return eq; + } + + public static Function CompileFunction(string eq) + { + string norm = NormalizeEquation(eq); + Function f = new Function(); + f.Parse(norm); + if (f.Error) + { + throw new ArgumentException("Denklem ayrıştırma hatası: " + f.ErrorDescription); + } + f.Infix2Postfix(); + return f; + } + + public static decimal EvaluateCompiled(Function f, string variable, decimal point) + { + f.SetVariable(variable, point); + f.EvaluatePostfix(); + if (f.Error) + { + throw new ArithmeticException(f.ErrorDescription); + } + return f.Result; + } + + public static decimal EvaluateCompiledMultiVar(Function f, Dictionary points) + { + f.SetVariables(points); + f.EvaluatePostfix(); + if (f.Error) + { + throw new ArithmeticException(f.ErrorDescription); + } + return f.Result; + } public static decimal Method_EvaluateFunction(string eq, string variable, decimal point) { - string newEq = eq; - newEq = newEq.Replace(variable, point.ToString(CultureInfo.InvariantCulture)); - Function f = new Function(); - f.Parse(newEq); - f.Infix2Postfix(); - f.EvaluatePostfix(); - return f.m_result; + Function f = CompileFunction(eq); + return EvaluateCompiled(f, variable, point); } public static decimal MethodMultiVar_EvaluateFunction(string eq, Dictionary points) { - string newEq = eq; - foreach (KeyValuePair pt in points) - { - newEq = newEq.Replace(pt.Key, pt.Value.ToString(CultureInfo.InvariantCulture)); - } - Function f = new Function(); - f.Parse(newEq); - f.Infix2Postfix(); - f.EvaluatePostfix(); - return f.m_result; + Function f = CompileFunction(eq); + return EvaluateCompiledMultiVar(f, points); } - public static Dictionary MethodMultiVar_SolveEquationSystem(List eqs, Dictionary initPoints, int iterationCount = 5, decimal h = 0.001m) + /// + /// Solves a nonlinear or linear system of equations using Multivariable Newton-Raphson with analytical/numerical Jacobian + /// and returns step-by-step convergence logs as well as the final solution dictionary. + /// + public static Dictionary MethodMultiVar_SolveEquationSystem( + List eqs, + Dictionary initPoints, + int iterationCount = 50, + decimal h = 0.0001m) { - Dictionary dynamicPoints = new Dictionary(initPoints); - for (int itC = 0; itC < iterationCount; itC++) - { - List linearizedEqs = new List(); - List variablesStr = new List(); - List leftVector = new List(); - - for (int i = 0; i < eqs.Count; i++) - { - string le = MethodMultiVar_TaylorSeries(eqs[i], 1, dynamicPoints, h); - - decimal leftV = 0; - Match m = Regex.Match(le, @"^([-+]?[0-9]*\.?[0-9]+)"); - if (m.Success) - { - if (m.Index + m.Length < le.Length && le[m.Index + m.Length] == '*') - { - leftV = 0; - } - else - { - leftV = decimal.Parse(m.Value, CultureInfo.InvariantCulture) * -1; - le = le.Substring(m.Length); - } - } - - string sum = ""; - foreach (KeyValuePair p in dynamicPoints) - { - sum += p.Key + ": " + p.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) + ", "; - } - - - - foreach (KeyValuePair p in dynamicPoints) - { - le = le.Replace("(" + p.Key + (p.Value < 0 ? "+" + DecimalMath.Abs(p.Value).ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : "-" + p.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture)) + ")", p.Key); - le = le.Replace("(" + p.Key + ")", p.Key); - } - - linearizedEqs.Add(le); - leftVector.Add(leftV); - } - - foreach (KeyValuePair p in dynamicPoints) - { - variablesStr.Add(p.Key); - } - - decimal[][] jacobianMatrix = Matrix.ConvertLinearEquationsToMatrix(linearizedEqs, variablesStr); - decimal[] leftHandVector = leftVector.ToArray(); - - // Using DotNetMatrix to solve J * delta = -F - // Verify if Matrix.SolveEquation is ported or if we should use GeneralMatrix - // Matrix.cs in core likely has SolveEquation if I ported it. - // Let's assume Matrix.cs has it or we use GeneralMatrix directly. - // The original used Matrix.SolveEquation. - // My ported Matrix.cs from step 20 (viewed 1-663) has SolveEquation. - - decimal[] newPoints = Matrix.SolveEquation(jacobianMatrix, leftHandVector); - - List newPointsList = new List(); - for (int i = 0; i < newPoints.Length; i++) - { - newPointsList.Add(newPoints[i]); - } - - Dictionary tempDynamicPoints = new Dictionary(); - foreach (KeyValuePair p in dynamicPoints) - { - tempDynamicPoints.Add(p.Key, p.Value); - } - - foreach (KeyValuePair p in dynamicPoints) - { - tempDynamicPoints[p.Key] = newPointsList[0] + p.Value; - newPointsList.RemoveAt(0); - } - dynamicPoints = tempDynamicPoints; - } - - return dynamicPoints; + var logs = new List(); + return SolveEquationSystemWithLogs(eqs, initPoints, iterationCount, out logs, h); } - public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.001m) + public static Dictionary SolveEquationSystemWithLogs( + List eqs, + Dictionary initPoints, + int iterationCount, + out List logs, + decimal h = 0.0001m) { + logs = new List(); + if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) + { + throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); + } + + int n = eqs.Count; + List vars = initPoints.Keys.ToList(); + Dictionary currentPoints = new Dictionary(initPoints); + + List compiledEqs = new List(n); + for (int i = 0; i < n; i++) + { + compiledEqs.Add(CompileFunction(eqs[i])); + } + + decimal tolerance = 0.0000000001m; // 1e-10m + + for (int iter = 1; iter <= iterationCount; iter++) + { + decimal[] F = new decimal[n]; + decimal maxAbsF = 0m; + + for (int i = 0; i < n; i++) + { + F[i] = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + decimal absF = DecimalMath.Abs(F[i]); + if (absF > maxAbsF) maxAbsF = absF; + } + + if (maxAbsF <= tolerance) + { + logs.Add($"[Adım {iter - 1}] Yakınsama sağlandı! Maksimum hata |F| = {maxAbsF:E4}"); + break; + } + + // Compute Jacobian Matrix J[i][j] = df_i / dx_j via central finite difference + decimal[][] J = new decimal[n][]; + for (int i = 0; i < n; i++) + { + J[i] = new decimal[n]; + for (int j = 0; j < n; j++) + { + string vName = vars[j]; + decimal origVal = currentPoints[vName]; + + currentPoints[vName] = origVal + h; + decimal fPlus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + + currentPoints[vName] = origVal - h; + decimal fMinus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + + currentPoints[vName] = origVal; + J[i][j] = (fPlus - fMinus) / (2m * h); + } + } + + decimal[] negF = new decimal[n]; + for (int i = 0; i < n; i++) negF[i] = -F[i]; + + decimal[] delta; + try + { + delta = Matrix.SolveEquation(J, negF); + } + catch + { + // Perturb slightly if Jacobian is singular at initial guess (e.g. (0,0) for x^2+y^2) + for (int j = 0; j < n; j++) + { + currentPoints[vars[j]] += 0.01m * (j + 1); + } + logs.Add($"[Adım {iter}] Jakobiyen matrisi tekil (singular) noktaya denk geldi, nokta hafifçe kaydırılıyor..."); + continue; + } + + decimal maxStep = 0m; + for (int j = 0; j < n; j++) + { + currentPoints[vars[j]] += delta[j]; + decimal absD = DecimalMath.Abs(delta[j]); + if (absD > maxStep) maxStep = absD; + } + + string ptSummary = string.Join(", ", vars.Select(v => $"{v} = {currentPoints[v].ToString("0.########", CultureInfo.InvariantCulture)}")); + logs.Add($"[Adım {iter}] {ptSummary} (|Δ| = {maxStep:E3})"); + + if (maxStep <= tolerance) + { + logs.Add($"[Adım {iter}] Çözüm başarıyla yakınsadı."); + break; + } + } + + return currentPoints; + } + + public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.005m) + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; decimal constant = Method_EvaluateFunction(eq, variable, point); - constant = DecimalMath.Abs(constant) <= 0.001m ? 0 : constant; - string newEq = constant != 0 ? constant.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : ""; - for (int i = 1; i < degree + 1; i++) + if (DecimalMath.Abs(constant) <= 0.000001m) constant = 0; + + List terms = new List(); + if (constant != 0) { - decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, h); + terms.Add(FormatCoeff(constant)); + } + + for (int i = 1; i <= degree; i++) + { + decimal step = i >= 4 ? 0.01m : h; + decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, step); decimal fact = Factorial(i); - decimal coeff = (der / fact); - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; + decimal coeff = der / fact; - string addingSTR = ""; - if (point < 0) - { - addingSTR = "+" + DecimalMath.Abs(point).ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); - } - else if (point > 0) - { - addingSTR = "-" + point.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); - } + if (DecimalMath.Abs(coeff) <= 0.000001m) continue; - varSTR += coeff.ToString(CultureInfo.InvariantCulture) + "*(" + variable + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) + ""); - newEq += varSTR; + string varPart = FormatVarPower(variable, point, i); + string coeffStr = FormatTermWithCoeff(coeff, varPart, terms.Count == 0); + terms.Add(coeffStr); } - if (constant == 0 && newEq.Length > 0 && newEq[0] == '+') newEq = newEq.Substring(1); - return newEq; + + if (terms.Count == 0) return "0"; + return string.Join(" ", terms); } - public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.001m) + public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.005m) { - decimal constant = MethodMultiVar_EvaluateFunction(eq, points); - constant = DecimalMath.Abs(constant) <= 0.0001m ? 0 : constant; - string newEq = constant != 0 ? constant.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : ""; - for (int i = 1; i < degree + 1; i++) + if (points == null || points.Count == 0) return "0"; + + Function compiled = CompileFunction(eq); + decimal constant = EvaluateCompiledMultiVar(compiled, points); + if (DecimalMath.Abs(constant) <= 0.00001m) constant = 0; + + List terms = new List(); + if (constant != 0) { - foreach (KeyValuePair pt in points) - { - decimal partDer = Method_NumericalPartialDifferentiation(eq, i, pt.Key, points, 4, h); - decimal fact = Factorial(i); - decimal coeff = partDer / fact; - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; + terms.Add(FormatCoeff(constant)); + } - string addingSTR = ""; - if (pt.Value < 0) + List varNames = points.Keys.ToList(); + int kVars = varNames.Count; + + for (int totalDeg = 1; totalDeg <= degree; totalDeg++) + { + List multiIndices = GenerateMultiIndices(kVars, totalDeg); + foreach (int[] alpha in multiIndices) + { + decimal mixedDer = ComputeMixedPartialDerivative(compiled, varNames, alpha, points, h); + decimal denom = 1m; + for (int j = 0; j < kVars; j++) { - addingSTR = "+" + DecimalMath.Abs(pt.Value).ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); + denom *= Factorial(alpha[j]); } - else if (pt.Value > 0) + + decimal coeff = mixedDer / denom; + if (DecimalMath.Abs(coeff) <= 0.00001m) continue; + + List factors = new List(); + for (int j = 0; j < kVars; j++) { - addingSTR = "-" + pt.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); + if (alpha[j] > 0) + { + string vName = varNames[j]; + factors.Add(FormatVarPower(vName, points[vName], alpha[j])); + } } - varSTR += coeff.ToString(CultureInfo.InvariantCulture) + "*(" + pt.Key + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture)); - newEq += varSTR; + + string varPart = string.Join(" * ", factors); + terms.Add(FormatTermWithCoeff(coeff, varPart, terms.Count == 0)); } } - if (constant == 0 && newEq.Length > 0 && newEq[0] == '+') newEq = newEq.Substring(1); - // Assuming intent was to do nothing or it's buggy. I'll leave it as is (or fix it). - return newEq; + + if (terms.Count == 0) return "0"; + return string.Join(" ", terms); } - public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.001m) + private static List GenerateMultiIndices(int numVars, int totalSum) { - // Lipschitz check suppressed/incomplete in original - decimal init = initialValue; + List results = new List(); + int[] current = new int[numVars]; + GenerateMultiIndicesRecursive(numVars, totalSum, 0, current, results); + return results; + } + + private static void GenerateMultiIndicesRecursive(int numVars, int remaining, int idx, int[] current, List results) + { + if (idx == numVars - 1) + { + current[idx] = remaining; + results.Add((int[])current.Clone()); + return; + } + for (int v = remaining; v >= 0; v--) + { + current[idx] = v; + GenerateMultiIndicesRecursive(numVars, remaining - v, idx + 1, current, results); + } + } + + private static decimal ComputeMixedPartialDerivative( + Function f, + List varNames, + int[] orders, + Dictionary basePoints, + decimal h) + { + Dictionary workPoints = new Dictionary(basePoints); + return ComputeMixedRecursive(f, varNames, orders, 0, workPoints, h); + } + + private static decimal ComputeMixedRecursive( + Function f, + List varNames, + int[] orders, + int varIndex, + Dictionary workPoints, + decimal h) + { + while (varIndex < orders.Length && orders[varIndex] == 0) + { + varIndex++; + } + + if (varIndex >= orders.Length) + { + return EvaluateCompiledMultiVar(f, workPoints); + } + + string vName = varNames[varIndex]; + int m = orders[varIndex]; + decimal origVal = workPoints[vName]; + + // Central finite difference weights for order m + decimal sum = 0m; + for (int i = 0; i <= m; i++) + { + decimal shift = (m - 2m * i) * (h * 0.5m); + workPoints[vName] = origVal + shift; + decimal sign = (i % 2 == 0) ? 1m : -1m; + decimal comb = Combination(m, i); + decimal subVal = ComputeMixedRecursive(f, varNames, orders, varIndex + 1, workPoints, h); + sum += sign * comb * subVal; + } + + workPoints[vName] = origVal; + return sum / DecimalMath.Pow(h, m); + } + + private static string FormatCoeff(decimal c) + { + decimal rounded = Math.Round(c, 6); + foreach (int denom in new[] { 1, 2, 3, 4, 6, 8, 12 }) + { + decimal candidate = Math.Round(c * denom) / (decimal)denom; + if (DecimalMath.Abs(c - candidate) < 0.00005m) + { + rounded = candidate; + break; + } + } + return rounded.ToString("0.######", CultureInfo.InvariantCulture); + } + + private static string FormatVarPower(string variable, decimal center, int power) + { + string core; + if (center == 0m) + { + core = variable; + } + else if (center > 0m) + { + core = $"({variable} - {FormatCoeff(center)})"; + } + else + { + core = $"({variable} + {FormatCoeff(DecimalMath.Abs(center))})"; + } + + if (power == 1) return core; + return $"{core}^{power}"; + } + + private static string FormatTermWithCoeff(decimal coeff, string varPart, bool isFirst) + { + decimal absC = DecimalMath.Abs(coeff); + string sign = coeff < 0 ? (isFirst ? "-" : "- ") : (isFirst ? "" : "+ "); + string cStr = FormatCoeff(absC); + + if (cStr == "1") + { + return $"{sign}{varPart}"; + } + return $"{sign}{cStr}*{varPart}"; + } + + public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.0001m) + { + Function f = CompileFunction(eq); + decimal curr = initialValue; for (int i = 0; i < iterationCount; i++) { - decimal next = init - Method_EvaluateFunction(eq, variable, init) / Method_NumericalDifferentiation(eq, 1, variable, init, 6, h); - init = next; - } - return init; - } + decimal fx = EvaluateCompiled(f, variable, curr); + if (DecimalMath.Abs(fx) <= 1e-12m) break; - // Overload for single-variable Newton-Raphson from UIController's simpler usage (assuming UIController calls this one if I didn't verify signature) - // UIController calls: NumericalMethods.Method_NewtonRaphson(eq, variable, initialP, iterCount); - // Matches the one above. - - // My previous implementation had a simplified one. I should keep the one matching signature. + decimal dfx = (EvaluateCompiled(f, variable, curr + h) - EvaluateCompiled(f, variable, curr - h)) / (2m * h); + if (DecimalMath.Abs(dfx) <= 1e-15m) break; + + curr = curr - fx / dfx; + } + return curr; + } public static decimal Method_BisectionMethod(string eq, string variable, decimal lowerValue, decimal higherValue, int iterationCount) { - if (lowerValue >= higherValue) - return 0; + if (lowerValue >= higherValue) return lowerValue; - decimal mp = (lowerValue + higherValue) / 2; + Function f = CompileFunction(eq); + decimal fa = EvaluateCompiled(f, variable, lowerValue); + if (DecimalMath.Abs(fa) <= 1e-12m) return lowerValue; + decimal fb = EvaluateCompiled(f, variable, higherValue); + if (DecimalMath.Abs(fb) <= 1e-12m) return higherValue; + + decimal mp = (lowerValue + higherValue) / 2m; for (int i = 0; i < iterationCount; i++) { - mp = (lowerValue + higherValue) / 2; + mp = (lowerValue + higherValue) / 2m; + decimal evMiddle = EvaluateCompiled(f, variable, mp); - decimal evLower = Method_EvaluateFunction(eq, variable, lowerValue); - // decimal evHigher = Method_EvaluateFunction(eq, variable, higherValue); // unused - decimal evMiddle = Method_EvaluateFunction(eq, variable, mp); + if (DecimalMath.Abs(evMiddle) <= 1e-12m) break; - if (evLower * evMiddle < 0) + if (fa * evMiddle <= 0) { higherValue = mp; + fb = evMiddle; } else { lowerValue = mp; + fa = evMiddle; } } @@ -235,34 +443,27 @@ public class NumericalMethods public static decimal Method_Derivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - decimal sum = 0; - for (int i = 0; i <= degree; i++) - { - sum += DecimalMath.Pow(-1, i) * Combination(degree, i) * Method_EvaluateFunction(eq, variable, point + (degree - i) * h); - } - return sum / DecimalMath.Pow(h, degree); + return Method_NumericalDifferentiation(eq, degree, variable, point, 4, h); } public static decimal Method_PartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) { - decimal sum = 0; - Dictionary testPS = new Dictionary(points); - decimal firstToVar = testPS[toVar]; - for (int i = 0; i <= degree; i++) - { - testPS[toVar] = firstToVar + (degree - i) * h; - sum += DecimalMath.Pow(-1, i) * Combination(degree, i) * MethodMultiVar_EvaluateFunction(eq, testPS); - } - return sum / DecimalMath.Pow(h, degree); + return Method_NumericalPartialDifferentiation(eq, degree, toVar, points, 4, h); } public static decimal Method_NumericalDifferentiation(string eq, int degree, string variable, decimal point, int accuracy = 2, decimal h = 0.001m) { int m = degree, n = accuracy; + if (m >= 11) { n = 2; h = 0.08m; } + else if (m == 10) { n = 2; h = 0.04m; } + else if (m == 9) { n = 4; h = 0.015m; } + else if (m >= 7 && h < 0.012m) h = 0.012m; + + Function f = CompileFunction(eq); int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; decimal[][] _matrix = new decimal[2 * p + 1][]; - decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], + decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], functionPointsY = new decimal[2 * p + 1]; for (int i = 0; i < _matrix.Length; i++) @@ -270,20 +471,12 @@ public class NumericalMethods _matrix[i] = new decimal[2 * p + 1]; for (int j = 0; j < _matrix[i].Length; j++) { - _matrix[i][j] = (decimal)Math.Pow(-p + j, i); - } - - if (i != m) - { - _rhsVector[i] = 0; - } - else if (i == m) - { - _rhsVector[i] = Factorial(m); + _matrix[i][j] = DecimalMath.PowerN(-p + j, i); } + _rhsVector[i] = (i == m) ? Factorial(m) : 0m; functionPointsX[i] = point - (p - i) * h; - functionPointsY[i] = Method_EvaluateFunction(eq, variable, functionPointsX[i]); + functionPointsY[i] = EvaluateCompiled(f, variable, functionPointsX[i]); } GeneralMatrix _A = new GeneralMatrix(_matrix); @@ -307,6 +500,7 @@ public class NumericalMethods public static decimal Method_NumericalPartialDifferentiation(string eq, int degree, string toVar, Dictionary points, int accuracy = 2, decimal h = 0.001m) { + Function f = CompileFunction(eq); int m = degree, n = accuracy; int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; @@ -319,11 +513,10 @@ public class NumericalMethods _matrix[i] = new decimal[2 * p + 1]; for (int j = 0; j < _matrix[i].Length; j++) { - _matrix[i][j] = (decimal)Math.Pow(-p + j, i); + _matrix[i][j] = DecimalMath.PowerN(-p + j, i); } - if (i != m) _rhsVector[i] = 0; - else if (i == m) _rhsVector[i] = Factorial(m); + _rhsVector[i] = (i == m) ? Factorial(m) : 0m; } foreach (KeyValuePair item in points) @@ -347,7 +540,7 @@ public class NumericalMethods { pair.Add(item.Key, item.Value[i]); } - functionPointsRange[i] = MethodMultiVar_EvaluateFunction(eq, pair); + functionPointsRange[i] = EvaluateCompiledMultiVar(f, pair); } GeneralMatrix _A = new GeneralMatrix(_matrix); @@ -368,18 +561,35 @@ public class NumericalMethods public static decimal Factorial(int num) { - if (num >= 2) return num * Factorial(num - 1); - else return 1; + if (num < 0) return 0m; + decimal res = 1m; + for (int i = 2; i <= num; i++) res *= i; + return res; } public static decimal Combination(int n, int k) { - return Factorial(n) / (Factorial(n - k) * Factorial(k)); + if (k < 0 || k > n || n < 0) return 0m; + if (k == 0 || k == n) return 1m; + if (k > n - k) k = n - k; + decimal res = 1m; + for (int i = 1; i <= k; i++) + { + res = (res * (n - k + i)) / i; + } + return res; } - + public static decimal Permutation(int n, int k) { - return Factorial(n) / Factorial(n - k); + if (k < 0 || k > n || n < 0) return 0m; + if (k == 0) return 1m; + decimal res = 1m; + for (int i = 0; i < k; i++) + { + res *= (n - i); + } + return res; } public static string GenerateCombinations(string chars, string prefix, int length) @@ -388,6 +598,7 @@ public class NumericalMethods GenerateCombinationsRecursive(prefix, chars, length, sb); return sb.ToString(); } + static void GenerateCombinationsRecursive(string prefix, string chars, int length, StringBuilder sb) { if (length == 0) @@ -402,142 +613,502 @@ public class NumericalMethods } } - // --- Added Linear Solvers (Optional but kept for completeness if UI uses them) --- - // Update: UI uses MethodMultiVar_SolveEquationSystem for System Solver now (based on UIController) - // But I implemented btnSolveSystem_Click in MainForm.cs to use Method_LUDecomposition previously. - // I should update MainForm.cs to use MethodMultiVar_SolveEquationSystem if it's non-linear or general. - // The original app used MethodMultiVar_SolveEquationSystem (Newton-Raphson) for general systems. - - // So I should keep MethodMultiVar_SolveEquationSystem and update MainForm to use IT instead of LUDecomposition if I want to match original behavior. - - // I'll keep the linear solvers just in case. - - public static List Method_Inverse(List _eq, List _vars) + /// + /// Gauss-Seidel Iterative Linear System Solver with Diagonal Dominance Verification & Row Reordering. + /// Ported and enhanced from NumericalMethods / NumericalMethods2. + /// + public static Dictionary Method_GaussSeidel( + List eqs, + Dictionary initPoints, + int iterationCount, + out List logs) { - // Implementation from previous turn - decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(_eq, _vars); - if (A == null) return null; - decimal[] B = new decimal[_eq.Count]; - for (int i = 0; i < _eq.Count; i++) + logs = new List(); + if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) { - int ind = _eq[i].IndexOf('='); - if (ind != -1) B[i] = decimal.Parse(_eq[i].Substring(ind + 1), CultureInfo.InvariantCulture); - else B[i] = 0; + throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); } - + + int n = eqs.Count; + List vars = initPoints.Keys.ToList(); + + // Extract linear matrix A and right-hand vector b such that A * x = b + // Note: ConvertLinearEquationsToMatrix evaluates f(x) = LHS - RHS = A*x - b + decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); + decimal[] b = new decimal[n]; + Dictionary zeroPts = new Dictionary(); + foreach (string v in vars) zeroPts[v] = 0m; + + for (int i = 0; i < n; i++) + { + string normEq = NormalizeEquation(eqs[i]); + // f(0) = -b => b = -f(0) + b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); + } + + // Check / reorder rows for diagonal dominance: |a_ii| > sum_{j != i} |a_ij| + int[] dominantColForRow = new int[n]; + bool strictDominance = true; + for (int i = 0; i < n; i++) + { + int domCol = -1; + for (int j = 0; j < n; j++) + { + decimal sumOthers = 0m; + for (int k = 0; k < n; k++) + { + if (k != j) sumOthers += DecimalMath.Abs(A[i][k]); + } + if (DecimalMath.Abs(A[i][j]) >= sumOthers && DecimalMath.Abs(A[i][j]) > 0m) + { + domCol = j; + break; + } + } + dominantColForRow[i] = domCol; + if (domCol == -1) strictDominance = false; + } + + // Attempt to permute rows if each row has a distinct dominant column + if (strictDominance && dominantColForRow.Distinct().Count() == n) + { + decimal[][] newA = new decimal[n][]; + decimal[] newB = new decimal[n]; + for (int i = 0; i < n; i++) + { + int targetRow = dominantColForRow[i]; + newA[targetRow] = A[i]; + newB[targetRow] = b[i]; + } + A = newA; + b = newB; + logs.Add("✓ Köşegen baskınlığı (Diagonal Dominance) doğrulandı (|a_ii| ≥ Σ|a_ij|)."); + } + else + { + logs.Add("⚠️ Uyarı: Matris tam köşegen baskın değil; Gauss-Seidel yakınsamayabilir."); + } + + decimal[] x = new decimal[n]; + for (int i = 0; i < n; i++) x[i] = initPoints[vars[i]]; + + decimal tol = 1e-10m; + for (int iter = 1; iter <= iterationCount; iter++) + { + decimal maxDiff = 0m; + for (int i = 0; i < n; i++) + { + if (DecimalMath.Abs(A[i][i]) <= 1e-15m) + { + throw new ArithmeticException($"Köşegen elemanı A[{i + 1},{i + 1}] = 0 olduğu için Gauss-Seidel uygulanamaz."); + } + + decimal sigma = 0m; + for (int j = 0; j < n; j++) + { + if (j != i) sigma += A[i][j] * x[j]; + } + + decimal nextXi = (b[i] - sigma) / A[i][i]; + decimal diff = DecimalMath.Abs(nextXi - x[i]); + if (diff > maxDiff) maxDiff = diff; + x[i] = nextXi; + } + + string stepStr = string.Join(", ", Enumerable.Range(0, n).Select(idx => $"{vars[idx]} = {x[idx].ToString("0.########", CultureInfo.InvariantCulture)}")); + logs.Add($"[Adım {iter,2}] {stepStr} (|Δ| = {maxDiff:E3})"); + + if (maxDiff <= tol) + { + logs.Add($"✓ Gauss-Seidel {iter}. adımda başarıyla yakınsadı."); + break; + } + } + + Dictionary result = new Dictionary(); + for (int i = 0; i < n; i++) result[vars[i]] = x[i]; + return result; + } + + public static Dictionary Method_LinearMatrixSolve( + List eqs, + List vars, + string methodType, + out List logs) + { + logs = new List(); + int n = eqs.Count; + decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); + decimal[] b = new decimal[n]; + + Dictionary zeroPts = new Dictionary(); + foreach (string v in vars) zeroPts[v] = 0m; + bool isNonLinear = false; + for (int i = 0; i < n; i++) + { + string normEq = NormalizeEquation(eqs[i]); + b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); + + if (vars.Count > 0) + { + zeroPts[vars[0]] = 2m; + decimal f2 = MethodMultiVar_EvaluateFunction(normEq, zeroPts); + zeroPts[vars[0]] = 0m; + if (DecimalMath.Abs(f2 - (2m * A[i][0] - b[i])) > 1e-4m) + { + isNonLinear = true; + } + } + } + + if (isNonLinear) + { + logs.Add("UYARI: Denklemler doğrusal değil. Çözüm doğrusal yaklaşım olarak sunulmuştur."); + } + + logs.Add("--- Katsayılar Matrisi (A) ve Sağ Taraf Vektörü (b) ---"); + for (int i = 0; i < n; i++) + { + string rowStr = string.Join(" ", A[i].Select(v => $"{v,8:0.####}")); + logs.Add($" [ {rowStr} ] | [ {b[i],8:0.####} ]"); + } + logs.Add(""); + GeneralMatrix gA = new GeneralMatrix(A); - GeneralMatrix gB = new GeneralMatrix(B, B.Length); - GeneralMatrix gX = gA.Solve(gB); - decimal[] X = gX.ColumnPackedCopy; - - List res = new List(); - for (int i = 0; i < X.Length; i++) res.Add(_vars[i] + " = " + X[i].ToString("F5", CultureInfo.InvariantCulture)); + GeneralMatrix gB = new GeneralMatrix(n, 1); + for (int i = 0; i < n; i++) gB.Array[i][0] = b[i]; + + GeneralMatrix gX; + if (methodType == "INVERSE") + { + logs.Add("Yöntem: Ters Matris (X = A⁻¹ · b)"); + GeneralMatrix invA = gA.Inverse(); + gX = invA.Multiply(gB); + } + else if (methodType == "QR") + { + logs.Add("Yöntem: QR Ayrışımı (Q·R·X = b)"); + gX = gA.QRD().Solve(gB); + } + else + { + logs.Add("Yöntem: LU Ayrışımı (L·U·X = P·b)"); + gX = gA.LUD().Solve(gB); + } + + Dictionary res = new Dictionary(); + for (int i = 0; i < n; i++) + { + res[vars[i]] = gX.Array[i][0]; + logs.Add($" {vars[i]} = {Math.Round(gX.Array[i][0], 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + } return res; } - public static List Method_LUDecomposition(List _eq, List _vars) + public static decimal Method_BackwardDifferenceDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - // Implementation from previous turn - decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(_eq, _vars); - if (A == null) return null; - decimal[] B = new decimal[_eq.Count]; - for (int i = 0; i < _eq.Count; i++) - { - int ind = _eq[i].IndexOf('='); - if (ind != -1) B[i] = decimal.Parse(_eq[i].Substring(ind + 1), CultureInfo.InvariantCulture); - else B[i] = 0; - } - - GeneralMatrix gA = new GeneralMatrix(A); - GeneralMatrix gB = new GeneralMatrix(B, B.Length); - GeneralMatrix gX = gA.Solve(gB); - decimal[] X = gX.ColumnPackedCopy; - - List res = new List(); - for (int i = 0; i < X.Length; i++) res.Add(_vars[i] + " = " + X[i].ToString("F5", CultureInfo.InvariantCulture)); - return res; + Function f = CompileFunction(eq); + decimal f0 = EvaluateCompiled(f, variable, point); + decimal f1 = EvaluateCompiled(f, variable, point - h); + decimal f2 = EvaluateCompiled(f, variable, point - 2m * h); + + if (degree == 1) + { + return (3m * f0 + f2 - 4m * f1) / (2m * h); + } + else if (degree == 2) + { + return (f0 + f2 - 2m * f1) / (h * h); + } + else if (degree == 3) + { + decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); + decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); + return (3m * f4 - 14m * f3 + 24m * f2 - 18m * f1 + 5m * f0) / (2m * h * h * h); + } + else if (degree == 4) + { + decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); + decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); + decimal f5 = EvaluateCompiled(f, variable, point - 5m * h); + return (-2m * f5 + 11m * f4 - 24m * f3 + 26m * f2 - 14m * f1 + 3m * f0) / (h * h * h * h); + } + else + { + return Method_ForwardBinomialDerivative(eq, degree, variable, point, h); + } } - // Additional wrappers for MainForm compatibility if needed - public static List Method_NewtonRaphson(string _eq, decimal _initialPoint, int _iterationCount) + public static decimal Method_ForwardBinomialDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - // Wrapper for UI - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - decimal res = Method_NewtonRaphson(_eq, "x", _initialPoint, _iterationCount); - return new List { res.ToString(CultureInfo.InvariantCulture) }; + Function f = CompileFunction(eq); + decimal sum = 0m; + for (int i = 0; i <= degree; i++) + { + decimal sign = (i % 2 == 0) ? 1m : -1m; + sum += sign * Combination(degree, i) * EvaluateCompiled(f, variable, point + (degree - i) * h); + } + return sum / DecimalMath.Pow(h, degree); } - - public static List Method_Bisection(string _eq, decimal _min, decimal _max, int _iterationCount) - { - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - decimal res = Method_BisectionMethod(_eq, "x", _min, _max, _iterationCount); - return new List { res.ToString(CultureInfo.InvariantCulture) }; - } - - public static List Method_Secant(string _eq, decimal _min, decimal _max, int _iterationCount) - { - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - - decimal x0 = _min; - decimal x1 = _max; - decimal x2 = 0; - - for(int i=0; i<_iterationCount; i++) - { - decimal f0 = Method_EvaluateFunction(_eq, "x", x0); - decimal f1 = Method_EvaluateFunction(_eq, "x", x1); - - if (f1 - f0 == 0) break; // Avoid divide by zero - - x2 = x1 - f1 * (x1 - x0) / (f1 - f0); - x0 = x1; - x1 = x2; - - if (DecimalMath.Abs(f1) < 0.00000001m) break; - } - - return new List { x2.ToString(CultureInfo.InvariantCulture) }; - } - public static List Method_RegulaFalsi(string _eq, decimal _min, decimal _max, int _iterationCount) + public static decimal Method_ForwardBinomialPartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) { - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - - decimal a = _min; - decimal b = _max; - decimal c = 0; - - for(int i=0; i<_iterationCount; i++) - { - decimal fa = Method_EvaluateFunction(_eq, "x", a); - decimal fb = Method_EvaluateFunction(_eq, "x", b); - - if (fa * fb >= 0) return new List { "Root not bracketed or multiple roots" }; - - c = (a * fb - b * fa) / (fb - fa); - decimal fc = Method_EvaluateFunction(_eq, "x", c); - - if (fc == 0) break; - else if (fa * fc < 0) b = c; - else a = c; - } - - return new List { c.ToString(CultureInfo.InvariantCulture) }; + Function f = CompileFunction(eq); + decimal sum = 0m; + Dictionary testPS = new Dictionary(points); + decimal firstToVar = testPS[toVar]; + for (int i = 0; i <= degree; i++) + { + testPS[toVar] = firstToVar + (degree - i) * h; + decimal sign = (i % 2 == 0) ? 1m : -1m; + sum += sign * Combination(degree, i) * EvaluateCompiledMultiVar(f, testPS); + } + return sum / DecimalMath.Pow(h, degree); + } + + // --- Root Finding Methods with Full Iteration Logs & Variable Support --- + + public static List Method_NewtonRaphson(string _eq, decimal _initialPoint, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + decimal x = _initialPoint; + decimal h = 0.0001m; + decimal tol = 1e-12m; + + logs.Add($"--- Newton-Raphson Yöntemi (Başlangıç: {variable}₀ = {x.ToString(CultureInfo.InvariantCulture)}) ---"); + + for (int i = 1; i <= _iterationCount; i++) + { + decimal fx = EvaluateCompiled(f, variable, x); + decimal dfx = (EvaluateCompiled(f, variable, x + h) - EvaluateCompiled(f, variable, x - h)) / (2m * h); + + if (DecimalMath.Abs(dfx) <= 1e-15m) + { + logs.Add($"[Adım {i}] Türev sıfıra çok yakın (f'({variable}) ≈ 0). İşlem durduruldu."); + break; + } + + decimal nextX = x - fx / dfx; + decimal err = DecimalMath.Abs(nextX - x); + x = nextX; + + logs.Add($"[Adım {i,2}] {variable} = {x.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fx.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (err <= tol || DecimalMath.Abs(fx) <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, x); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {x.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_Bisection(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal a = _min; + decimal b = _max; + if (a >= b) + { + return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; + } + + decimal fa = EvaluateCompiled(f, variable, a); + decimal fb = EvaluateCompiled(f, variable, b); + + if (DecimalMath.Abs(fa) <= 1e-12m) + { + logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + if (DecimalMath.Abs(fb) <= 1e-12m) + { + logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + + if (fa * fb > 0) + { + return new List + { + $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", + $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", + "Bisection (İkiye Bölme) yöntemi için f(Min) * f(Max) <= 0 olmalıdır." + }; + } + + logs.Add($"--- Bisection (İkiye Bölme) Yöntemi [{a}, {b}] ---"); + decimal mid = (a + b) / 2m; + decimal tol = 1e-11m; + + for (int i = 1; i <= _iterationCount; i++) + { + mid = (a + b) / 2m; + decimal fMid = EvaluateCompiled(f, variable, mid); + decimal width = (b - a) / 2m; + + logs.Add($"[Adım {i,2}] {variable} = {mid.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fMid.ToString("E3", CultureInfo.InvariantCulture),-11} | Aralık: [{a:0.####}, {b:0.####}]"); + + if (DecimalMath.Abs(fMid) <= tol || width <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + + if (fa * fMid <= 0) + { + b = mid; + fb = fMid; + } + else + { + a = mid; + fa = fMid; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, mid); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {mid.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_Secant(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal x0 = _min; + decimal x1 = _max; + decimal x2 = x1; + decimal tol = 1e-11m; + + logs.Add($"--- Secant (Kiriş) Yöntemi ({variable}₀ = {x0}, {variable}₁ = {x1}) ---"); + + for (int i = 1; i <= _iterationCount; i++) + { + decimal f0 = EvaluateCompiled(f, variable, x0); + decimal f1 = EvaluateCompiled(f, variable, x1); + + if (DecimalMath.Abs(f1 - f0) <= 1e-15m) + { + logs.Add($"[Adım {i}] f({variable}₁) - f({variable}₀) ≈ 0 oldu. İşlem durduruldu."); + break; + } + + x2 = x1 - f1 * (x1 - x0) / (f1 - f0); + decimal err = DecimalMath.Abs(x2 - x1); + x0 = x1; + x1 = x2; + + decimal f2 = EvaluateCompiled(f, variable, x2); + logs.Add($"[Adım {i,2}] {variable} = {x2.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {f2.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (err <= tol || DecimalMath.Abs(f2) <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, x2); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {x2.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_RegulaFalsi(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal a = _min; + decimal b = _max; + if (a >= b) + { + return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; + } + + decimal fa = EvaluateCompiled(f, variable, a); + decimal fb = EvaluateCompiled(f, variable, b); + + if (DecimalMath.Abs(fa) <= 1e-12m) + { + logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + if (DecimalMath.Abs(fb) <= 1e-12m) + { + logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + + if (fa * fb > 0) + { + return new List + { + $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", + $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", + "Regula Falsi yöntemi için f(Min) * f(Max) <= 0 olmalıdır." + }; + } + + logs.Add($"--- Regula Falsi (Yer Değiştirme) Yöntemi [{a}, {b}] ---"); + decimal c = a; + decimal tol = 1e-11m; + int side = 0; + + for (int i = 1; i <= _iterationCount; i++) + { + if (DecimalMath.Abs(fb - fa) <= 1e-15m) break; + + decimal prevC = c; + c = (a * fb - b * fa) / (fb - fa); + decimal fc = EvaluateCompiled(f, variable, c); + decimal err = DecimalMath.Abs(c - prevC); + + logs.Add($"[Adım {i,2}] {variable} = {c.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fc.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (DecimalMath.Abs(fc) <= tol || (i > 1 && err <= tol)) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + + if (fa * fc <= 0) + { + b = c; + fb = fc; + if (side == -1) fa *= 0.5m; + side = -1; + } + else + { + a = c; + fa = fc; + if (side == 1) fb *= 0.5m; + side = 1; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, c); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {c.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; } } diff --git a/MathApp/MathApp/GenerateLogo.ps1 b/MathApp/MathApp/GenerateLogo.ps1 index fcb9f00..993fb47 100644 --- a/MathApp/MathApp/GenerateLogo.ps1 +++ b/MathApp/MathApp/GenerateLogo.ps1 @@ -1,37 +1,211 @@ - +$ErrorActionPreference = "Stop" Add-Type -AssemblyName System.Drawing -$width = 256 -$height = 256 -$bmp = New-Object System.Drawing.Bitmap $width, $height -$g = [System.Drawing.Graphics]::FromImage($bmp) -$g.Clear([System.Drawing.Color]::FromArgb(30,30,30)) -$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias -$pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::FromArgb(0, 188, 212)), 12 -$points = @( - New-Object System.Drawing.PointF 128, 30 - New-Object System.Drawing.PointF 213, 79 - New-Object System.Drawing.PointF 213, 177 - New-Object System.Drawing.PointF 128, 226 - New-Object System.Drawing.PointF 43, 177 - New-Object System.Drawing.PointF 43, 79 -) -$g.DrawPolygon($pen, $points) +function Create-IconBitmap([int]$size) { + $bmp = New-Object System.Drawing.Bitmap($size, $size, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb) + $g = [System.Drawing.Graphics]::FromImage($bmp) + $g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality + $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic + $g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality + $g.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit + $g.Clear([System.Drawing.Color]::Transparent) -$font = New-Object System.Drawing.Font "Segoe UI", 110, [System.Drawing.FontStyle]::Bold -$brush = [System.Drawing.Brushes]::White -$format = New-Object System.Drawing.StringFormat -$format.Alignment = [System.Drawing.StringAlignment]::Center -$format.LineAlignment = [System.Drawing.StringAlignment]::Center -$g.DrawString("M", $font, $brush, 130, 135, $format) + $s = [float]$size / 256.0 -$iconName = "c:/Users/tolga/Desktop/Math/MathApp/MathApp/logo.ico" -$hicon = $bmp.GetHicon() -$icon = [System.Drawing.Icon]::FromHandle([IntPtr]$hicon) + # 1. Rounded Square Background + $margin = 12.0 * $s + $rectSize = $size - (2.0 * $margin) + $radius = 54.0 * $s + $d = $radius * 2.0 -$fs = [System.IO.File]::OpenWrite($iconName) -$icon.Save($fs) + $path = New-Object System.Drawing.Drawing2D.GraphicsPath + $path.AddArc($margin, $margin, $d, $d, 180, 90) + $path.AddArc($margin + $rectSize - $d, $margin, $d, $d, 270, 90) + $path.AddArc($margin + $rectSize - $d, $margin + $rectSize - $d, $d, $d, 0, 90) + $path.AddArc($margin, $margin + $rectSize - $d, $d, $d, 90, 90) + $path.CloseFigure() + + $rect = New-Object System.Drawing.RectangleF($margin, $margin, $rectSize, $rectSize) + $bgBrush = New-Object System.Drawing.Drawing2D.LinearGradientBrush( + $rect, + [System.Drawing.Color]::FromArgb(255, 17, 24, 39), + [System.Drawing.Color]::FromArgb(255, 10, 15, 29), + 45.0 + ) + $g.FillPath($bgBrush, $path) + + # Subtle inner glow / grid lines clipped to rounded rect + $g.SetClip($path) + + $gridPen = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(22, 56, 189, 248), [Math]::Max(1.0, 1.5 * $s)) + for ($i = 1; $i -le 4; $i++) { + $pos = $margin + ($rectSize * $i / 5.0) + $g.DrawLine($gridPen, $pos, $margin, $pos, $margin + $rectSize) + $g.DrawLine($gridPen, $margin, $pos, $margin + $rectSize, $pos) + } + + # 2. Glowing Sine Wave / Graph Curve across the background + $curvePts = New-Object 'System.Collections.Generic.List[System.Drawing.PointF]' + for ($x = 0; $x -le 100; $x++) { + $px = $margin + ($x / 100.0) * $rectSize + $t = ($x / 100.0) * [Math]::PI * 2.2 - 0.5 + $py = ($size * 0.62) - [Math]::Sin($t) * (36.0 * $s) - ($x / 100.0) * (24.0 * $s) + $curvePts.Add((New-Object System.Drawing.PointF($px, $py))) + } + $ptsArray = $curvePts.ToArray() + + # Glow layers + $glowPen1 = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(35, 14, 165, 233), (18.0 * $s)) + $glowPen1.StartCap = [System.Drawing.Drawing2D.LineCap]::Round + $glowPen1.EndCap = [System.Drawing.Drawing2D.LineCap]::Round + $g.DrawCurve($glowPen1, $ptsArray) + + $glowPen2 = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(80, 56, 189, 248), (10.0 * $s)) + $glowPen2.StartCap = [System.Drawing.Drawing2D.LineCap]::Round + $glowPen2.EndCap = [System.Drawing.Drawing2D.LineCap]::Round + $g.DrawCurve($glowPen2, $ptsArray) + + $curvePen = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(240, 56, 189, 248), [Math]::Max(1.5, 4.5 * $s)) + $curvePen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round + $curvePen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round + $g.DrawCurve($curvePen, $ptsArray) + + # 3. Matrix Brackets [ ] on left and right inside + $bracketPen = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(140, 129, 140, 248), [Math]::Max(1.5, 5.0 * $s)) + $bTop = 52.0 * $s + $bBot = 204.0 * $s + $bLeft = 40.0 * $s + $bRight = 216.0 * $s + $bTick = 16.0 * $s + + # Left bracket + $g.DrawLine($bracketPen, $bLeft + $bTick, $bTop, $bLeft, $bTop) + $g.DrawLine($bracketPen, $bLeft, $bTop, $bLeft, $bBot) + $g.DrawLine($bracketPen, $bLeft, $bBot, $bLeft + $bTick, $bBot) + + # Right bracket + $g.DrawLine($bracketPen, $bRight - $bTick, $bTop, $bRight, $bTop) + $g.DrawLine($bracketPen, $bRight, $bTop, $bRight, $bBot) + $g.DrawLine($bracketPen, $bRight, $bBot, $bRight - $bTick, $bBot) + + # 4. Main Center Typography "f(x)" + Integral/Function accent + $fHook = [char]0x0192 + $fText = "${fHook}(x)" + if ($size -ge 32) { + $fontMain = New-Object System.Drawing.Font("Segoe UI", (76.0 * $s), ([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Italic), [System.Drawing.GraphicsUnit]::Pixel) + $sf = New-Object System.Drawing.StringFormat + $sf.Alignment = [System.Drawing.StringAlignment]::Center + $sf.LineAlignment = [System.Drawing.StringAlignment]::Center + + # Drop shadow + $shadowBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(170, 0, 0, 0)) + $g.DrawString($fText, $fontMain, $shadowBrush, ($size / 2.0) + (3.0 * $s), ($size * 0.43) + (4.0 * $s), $sf) + + $textBrush = New-Object System.Drawing.Drawing2D.LinearGradientBrush( + (New-Object System.Drawing.PointF(0, ($size * 0.18))), + (New-Object System.Drawing.PointF(0, ($size * 0.72))), + [System.Drawing.Color]::FromArgb(255, 255, 255, 255), + [System.Drawing.Color]::FromArgb(255, 186, 230, 253) + ) + $g.DrawString($fText, $fontMain, $textBrush, ($size / 2.0), ($size * 0.43), $sf) + + # Small badge "ttCalc" at bottom + $fontSub = New-Object System.Drawing.Font("Consolas", (28.0 * $s), [System.Drawing.FontStyle]::Bold, [System.Drawing.GraphicsUnit]::Pixel) + $subBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(240, 56, 189, 248)) + $g.DrawString("ttCalc", $fontSub, $subBrush, ($size / 2.0), ($size * 0.79), $sf) + + $fontMain.Dispose() + $fontSub.Dispose() + $shadowBrush.Dispose() + $textBrush.Dispose() + $subBrush.Dispose() + $sf.Dispose() + } else { + $fontSmall = New-Object System.Drawing.Font("Segoe UI", (115.0 * $s), ([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Italic), [System.Drawing.GraphicsUnit]::Pixel) + $sf = New-Object System.Drawing.StringFormat + $sf.Alignment = [System.Drawing.StringAlignment]::Center + $sf.LineAlignment = [System.Drawing.StringAlignment]::Center + $g.DrawString("$fHook", $fontSmall, [System.Drawing.Brushes]::White, ($size / 2.0), ($size * 0.48), $sf) + $fontSmall.Dispose() + $sf.Dispose() + } + + $g.ResetClip() + + # Outer glowing border + $borderBrush = New-Object System.Drawing.Drawing2D.LinearGradientBrush( + $rect, + [System.Drawing.Color]::FromArgb(220, 56, 189, 248), + [System.Drawing.Color]::FromArgb(180, 99, 102, 241), + 45.0 + ) + $borderPen = New-Object System.Drawing.Pen($borderBrush, [Math]::Max(1.5, 6.0 * $s)) + $g.DrawPath($borderPen, $path) + + $borderPen.Dispose() + $borderBrush.Dispose() + $bracketPen.Dispose() + $curvePen.Dispose() + $glowPen1.Dispose() + $glowPen2.Dispose() + $gridPen.Dispose() + $bgBrush.Dispose() + $path.Dispose() + $g.Dispose() + + return $bmp +} + +$sizes = @(16, 32, 48, 64, 128, 256) +$pngStreams = @() + +foreach ($sz in $sizes) { + $bmp = Create-IconBitmap $sz + if ($sz -eq 256) { + $pngPath = Join-Path $PSScriptRoot "logo_preview.png" + $bmp.Save($pngPath, [System.Drawing.Imaging.ImageFormat]::Png) + } + $ms = New-Object System.IO.MemoryStream + $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png) + $pngStreams += ,@($sz, $ms.ToArray()) + $ms.Dispose() + $bmp.Dispose() +} + +$icoPath = Join-Path $PSScriptRoot "logo.ico" +$fs = [System.IO.File]::Create($icoPath) +$bw = New-Object System.IO.BinaryWriter($fs) + +# ICONDIR Header +$bw.Write([uint16]0) # Reserved +$bw.Write([uint16]1) # Type: 1 = ICO +$bw.Write([uint16]$sizes.Count) # Count + +$offset = 6 + (16 * $sizes.Count) + +foreach ($entry in $pngStreams) { + $sz = $entry[0] + $bytes = $entry[1] + $wByte = if ($sz -ge 256) { [byte]0 } else { [byte]$sz } + $hByte = if ($sz -ge 256) { [byte]0 } else { [byte]$sz } + + $bw.Write($wByte) + $bw.Write($hByte) + $bw.Write([byte]0) # ColorCount + $bw.Write([byte]0) # Reserved + $bw.Write([uint16]1) # Planes + $bw.Write([uint16]32) # BitCount + $bw.Write([uint32]$bytes.Length) # BytesInRes + $bw.Write([uint32]$offset) # ImageOffset + $offset += $bytes.Length +} + +foreach ($entry in $pngStreams) { + $bytes = $entry[1] + $bw.Write($bytes) +} + +$bw.Flush() +$bw.Close() $fs.Close() -$g.Dispose() -$bmp.Dispose() -Write-Host "Logo created successfully at $iconName" +Write-Host "Multi-resolution ICO and preview PNG generated successfully at $icoPath" diff --git a/MathApp/MathApp/MainForm.Designer.cs b/MathApp/MathApp/MainForm.Designer.cs index 66bafe2..c288b66 100644 --- a/MathApp/MathApp/MainForm.Designer.cs +++ b/MathApp/MathApp/MainForm.Designer.cs @@ -1,3 +1,6 @@ +using System; +using System.Drawing; +using System.Windows.Forms; namespace MathApp { @@ -16,124 +19,185 @@ namespace MathApp private void InitializeComponent() { - this.pnlSidebar = new System.Windows.Forms.Panel(); - this.pnlContent = new System.Windows.Forms.Panel(); - this.btnNavCalc = new System.Windows.Forms.Button(); - this.btnNavRoot = new System.Windows.Forms.Button(); - this.btnNavSystem = new System.Windows.Forms.Button(); - this.pnlLogo = new System.Windows.Forms.Panel(); - this.lblLogo = new System.Windows.Forms.Label(); + this.pnlSidebar = new Panel(); + this.pnlNavButtons = new Panel(); + this.pnlContent = new Panel(); + this.pnlLogo = new Panel(); + this.lblLogo = new Label(); + this.lblLogoSub = new Label(); + this.lblVersion = new Label(); - this.btnNavTaylor = new System.Windows.Forms.Button(); - this.btnNavMultiTaylor = new System.Windows.Forms.Button(); // New - this.btnNavGraph = new System.Windows.Forms.Button(); + this.lblCat1 = new Label(); + this.btnNavCalc = new Button(); + this.btnNavGraph = new Button(); + this.btnNavCombinatorics = new Button(); + + this.lblCat2 = new Label(); + this.btnNavRoot = new Button(); + this.btnNavSystem = new Button(); + this.btnNavDerivative = new Button(); + + this.lblCat3 = new Label(); + this.btnNavMatrix = new Button(); + this.btnNavTaylor = new Button(); + this.btnNavMultiTaylor = new Button(); this.pnlSidebar.SuspendLayout(); + this.pnlNavButtons.SuspendLayout(); this.pnlLogo.SuspendLayout(); this.SuspendLayout(); - // - // pnlSidebar - // - this.pnlSidebar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); - this.pnlSidebar.Controls.Add(this.btnNavGraph); - this.pnlSidebar.Controls.Add(this.btnNavMultiTaylor); // New - this.pnlSidebar.Controls.Add(this.btnNavTaylor); - this.pnlSidebar.Controls.Add(this.btnNavSystem); - this.pnlSidebar.Controls.Add(this.btnNavRoot); - this.pnlSidebar.Controls.Add(this.btnNavCalc); - this.pnlSidebar.Controls.Add(this.pnlLogo); - this.pnlSidebar.Dock = System.Windows.Forms.DockStyle.Right; // Sidebar on Right as requested - this.pnlSidebar.Location = new System.Drawing.Point(600, 0); - this.pnlSidebar.Name = "pnlSidebar"; - this.pnlSidebar.Size = new System.Drawing.Size(200, 600); - this.pnlSidebar.TabIndex = 0; + // pnlSidebar (Left Navigation Bar) + this.pnlSidebar.BackColor = ThemeHelper.SidebarBackground; + this.pnlSidebar.Dock = DockStyle.Left; + this.pnlSidebar.Width = 245; + this.pnlSidebar.Padding = new Padding(8, 0, 8, 8); - // // pnlLogo - // + this.pnlLogo.Dock = DockStyle.Top; + this.pnlLogo.Height = 80; + this.pnlLogo.Padding = new Padding(10, 12, 10, 6); + + this.lblLogo.Dock = DockStyle.Top; + this.lblLogo.Height = 32; + this.lblLogo.Font = new Font("Segoe UI Semibold", 16F, FontStyle.Bold); + this.lblLogo.ForeColor = Color.FromArgb(56, 189, 248); + this.lblLogo.Text = "ƒ(x) ttCalculator"; + this.lblLogo.TextAlign = ContentAlignment.MiddleLeft; + + this.lblLogoSub.Dock = DockStyle.Top; + this.lblLogoSub.Height = 20; + this.lblLogoSub.Font = new Font("Segoe UI", 8.5F, FontStyle.Regular); + this.lblLogoSub.ForeColor = ThemeHelper.MutedText; + this.lblLogoSub.Text = "Nümerik Matematik Stüdyosu"; + this.lblLogoSub.TextAlign = ContentAlignment.MiddleLeft; + + this.pnlLogo.Controls.Add(this.lblLogoSub); this.pnlLogo.Controls.Add(this.lblLogo); - this.pnlLogo.Dock = System.Windows.Forms.DockStyle.Top; - this.pnlLogo.Location = new System.Drawing.Point(0, 0); - this.pnlLogo.Name = "pnlLogo"; - this.pnlLogo.Size = new System.Drawing.Size(200, 100); - this.pnlLogo.TabIndex = 0; - // - // lblLogo - // - this.lblLogo.Dock = System.Windows.Forms.DockStyle.Fill; - this.lblLogo.Font = new System.Drawing.Font("Segoe UI Light", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - this.lblLogo.ForeColor = System.Drawing.Color.White; - this.lblLogo.Location = new System.Drawing.Point(0, 0); - this.lblLogo.Name = "lblLogo"; - this.lblLogo.Size = new System.Drawing.Size(200, 100); - this.lblLogo.TabIndex = 0; - this.lblLogo.Text = "Math App"; - this.lblLogo.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // pnlNavButtons container with autoscroll support + this.pnlNavButtons.Dock = DockStyle.Fill; + this.pnlNavButtons.AutoScroll = true; - // Helper for Nav Buttons - void StyleNavButton(System.Windows.Forms.Button btn, string text, int index) + void StyleNavCategory(Label lbl, string text) { - btn.Dock = System.Windows.Forms.DockStyle.Top; - btn.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - btn.FlatAppearance.BorderSize = 0; - btn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(60, 60, 60); - btn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(0, 120, 215); - btn.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); - btn.ForeColor = System.Drawing.Color.White; - btn.Location = new System.Drawing.Point(0, 100 + (index * 60)); - btn.Name = "btnNav" + index; - btn.Size = new System.Drawing.Size(200, 60); - btn.TabIndex = index + 1; - btn.Text = text; - btn.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - btn.Padding = new System.Windows.Forms.Padding(20, 0, 0, 0); - btn.UseVisualStyleBackColor = true; + lbl.Dock = DockStyle.Top; + lbl.Height = 28; + lbl.Text = text; + lbl.Font = new Font("Segoe UI Semibold", 8F, FontStyle.Bold); + lbl.ForeColor = Color.FromArgb(100, 116, 139); + lbl.TextAlign = ContentAlignment.BottomLeft; + lbl.Padding = new Padding(12, 0, 0, 4); } - StyleNavButton(this.btnNavCalc, "Calculator", 0); - StyleNavButton(this.btnNavRoot, "Root Finder", 1); - StyleNavButton(this.btnNavSystem, "System Solver", 2); - StyleNavButton(this.btnNavTaylor, "Taylor Series", 3); - StyleNavButton(this.btnNavMultiTaylor, "MultiVar Taylor", 4); // New - StyleNavButton(this.btnNavGraph, "Graph Plotter", 5); + void StyleNavButton(Button btn, string text, int index) + { + btn.Dock = DockStyle.Top; + btn.FlatStyle = FlatStyle.Flat; + btn.FlatAppearance.BorderSize = 0; + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(30, 41, 59); + btn.FlatAppearance.MouseDownBackColor = ThemeHelper.AccentBlue; + btn.Font = new Font("Segoe UI", 9.5F, FontStyle.Regular); + btn.ForeColor = Color.FromArgb(203, 213, 225); + btn.Size = new Size(229, 38); + btn.TabIndex = index + 1; + btn.Text = text; + btn.TextAlign = ContentAlignment.MiddleLeft; + btn.Padding = new Padding(14, 0, 0, 0); + btn.Cursor = Cursors.Hand; + btn.UseVisualStyleBackColor = false; + } + + // Categories + StyleNavCategory(this.lblCat1, "HESAPLAMA & TEMEL"); + StyleNavButton(this.btnNavCalc, "🧮 Hesap Makinesi", 0); + StyleNavButton(this.btnNavGraph, "📈 Grafik Çizici", 1); + StyleNavButton(this.btnNavCombinatorics, "🎲 Kombinatorik & Özel", 2); + + StyleNavCategory(this.lblCat2, "NÜMERİK ANALİZ"); + StyleNavButton(this.btnNavRoot, "🔍 Denklem Kökü Bulucu", 3); + StyleNavButton(this.btnNavSystem, "⚡ Denklem Sistemi Çözücü", 4); + StyleNavButton(this.btnNavDerivative, "∂ Türev & Gradyan", 5); + + StyleNavCategory(this.lblCat3, "LİNEER CEBİR & SERİLER"); + StyleNavButton(this.btnNavMatrix, "🔢 Matris & Ayrışım", 6); + StyleNavButton(this.btnNavTaylor, "📐 Taylor Serisi (1D)", 7); + StyleNavButton(this.btnNavMultiTaylor, "🌐 Çok Değişkenli Taylor", 8); + + // Footer version label + this.lblVersion.Dock = DockStyle.Bottom; + this.lblVersion.Height = 26; + this.lblVersion.Text = "v2.0 • 128-bit Decimal Motoru"; + this.lblVersion.Font = new Font("Segoe UI", 8F); + this.lblVersion.ForeColor = Color.FromArgb(100, 116, 139); + this.lblVersion.TextAlign = ContentAlignment.MiddleCenter; + + // Add navigation controls in reverse order for DockStyle.Top inside pnlNavButtons + // Group 3 + this.pnlNavButtons.Controls.Add(this.btnNavMultiTaylor); + this.pnlNavButtons.Controls.Add(this.btnNavTaylor); + this.pnlNavButtons.Controls.Add(this.btnNavMatrix); + this.pnlNavButtons.Controls.Add(this.lblCat3); + + // Group 2 + this.pnlNavButtons.Controls.Add(this.btnNavDerivative); + this.pnlNavButtons.Controls.Add(this.btnNavSystem); + this.pnlNavButtons.Controls.Add(this.btnNavRoot); + this.pnlNavButtons.Controls.Add(this.lblCat2); + + // Group 1 + this.pnlNavButtons.Controls.Add(this.btnNavCombinatorics); + this.pnlNavButtons.Controls.Add(this.btnNavGraph); + this.pnlNavButtons.Controls.Add(this.btnNavCalc); + this.pnlNavButtons.Controls.Add(this.lblCat1); + + // Assemble pnlSidebar + this.pnlSidebar.Controls.Add(this.pnlNavButtons); + this.pnlSidebar.Controls.Add(this.pnlLogo); + this.pnlSidebar.Controls.Add(this.lblVersion); - // // pnlContent - // - this.pnlContent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); // Dark Content Area - this.pnlContent.Dock = System.Windows.Forms.DockStyle.Fill; - this.pnlContent.Location = new System.Drawing.Point(0, 0); - this.pnlContent.Name = "pnlContent"; - this.pnlContent.Size = new System.Drawing.Size(600, 600); - this.pnlContent.TabIndex = 1; + this.pnlContent.BackColor = ThemeHelper.DarkBackground; + this.pnlContent.Dock = DockStyle.Fill; - // // MainForm - // - this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 600); + this.AutoScaleDimensions = new SizeF(7F, 15F); + this.AutoScaleMode = AutoScaleMode.Font; + this.ClientSize = new Size(1180, 740); + this.MinimumSize = new Size(1020, 660); + this.StartPosition = FormStartPosition.CenterScreen; this.Controls.Add(this.pnlContent); this.Controls.Add(this.pnlSidebar); this.Name = "MainForm"; - this.Text = "Math Application"; + this.Text = "ttCalculator — Gelişmiş Matematik & Nümerik Analiz Stüdyosu"; + this.pnlSidebar.ResumeLayout(false); + this.pnlNavButtons.ResumeLayout(false); this.pnlLogo.ResumeLayout(false); this.ResumeLayout(false); - } - private System.Windows.Forms.Panel pnlSidebar; - private System.Windows.Forms.Panel pnlContent; - private System.Windows.Forms.Button btnNavCalc; - private System.Windows.Forms.Button btnNavRoot; - private System.Windows.Forms.Button btnNavSystem; - private System.Windows.Forms.Button btnNavTaylor; - private System.Windows.Forms.Button btnNavMultiTaylor; // New - private System.Windows.Forms.Button btnNavGraph; - private System.Windows.Forms.Panel pnlLogo; - private System.Windows.Forms.Label lblLogo; + private Panel pnlSidebar; + private Panel pnlNavButtons; + private Panel pnlContent; + private Panel pnlLogo; + private Label lblLogo; + private Label lblLogoSub; + private Label lblVersion; + + private Label lblCat1; + private Button btnNavCalc; + private Button btnNavGraph; + private Button btnNavCombinatorics; + + private Label lblCat2; + private Button btnNavRoot; + private Button btnNavSystem; + private Button btnNavDerivative; + + private Label lblCat3; + private Button btnNavMatrix; + private Button btnNavTaylor; + private Button btnNavMultiTaylor; } } diff --git a/MathApp/MathApp/MainForm.cs b/MathApp/MathApp/MainForm.cs index 2c0f6a7..2165198 100644 --- a/MathApp/MathApp/MainForm.cs +++ b/MathApp/MathApp/MainForm.cs @@ -1,5 +1,6 @@ using System; using System.Drawing; +using System.IO; using System.Windows.Forms; using MathApp.Controls; @@ -10,18 +11,21 @@ namespace MathApp private SimpleCalculatorControl calcControl; private RootFinderControl rootControl; private SystemSolverControl systemControl; + private MatrixCalculatorControl matrixControl; + private DerivativeCalculatorControl derivativeControl; private TaylorSeriesControl taylorControl; private MultivariableTaylorControl multiTaylorControl; + private CombinatoricsControl combinatoricsControl; private GraphPlotterControl graphControl; public MainForm() { InitializeComponent(); - try { this.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch { } - + LoadApplicationIcon(); + ThemeHelper.ApplyTheme(this); InitializeControls(); - + // Default View ShowControl(calcControl); HighlightButton(btnNavCalc); @@ -29,51 +33,85 @@ namespace MathApp btnNavCalc.Click += (s, e) => { ShowControl(calcControl); HighlightButton(btnNavCalc); }; btnNavRoot.Click += (s, e) => { ShowControl(rootControl); HighlightButton(btnNavRoot); }; btnNavSystem.Click += (s, e) => { ShowControl(systemControl); HighlightButton(btnNavSystem); }; + btnNavMatrix.Click += (s, e) => { ShowControl(matrixControl); HighlightButton(btnNavMatrix); }; + btnNavDerivative.Click += (s, e) => { ShowControl(derivativeControl); HighlightButton(btnNavDerivative); }; btnNavTaylor.Click += (s, e) => { ShowControl(taylorControl); HighlightButton(btnNavTaylor); }; btnNavMultiTaylor.Click += (s, e) => { ShowControl(multiTaylorControl); HighlightButton(btnNavMultiTaylor); }; + btnNavCombinatorics.Click += (s, e) => { ShowControl(combinatoricsControl); HighlightButton(btnNavCombinatorics); }; btnNavGraph.Click += (s, e) => { ShowControl(graphControl); HighlightButton(btnNavGraph); }; } + private void LoadApplicationIcon() + { + try + { + string icoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logo.ico"); + if (File.Exists(icoPath)) + { + this.Icon = new Icon(icoPath); + } + else + { + this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); + } + } + catch { } + } + private void InitializeControls() { - calcControl = new SimpleCalculatorControl(); - calcControl.Dock = DockStyle.Fill; - - rootControl = new RootFinderControl(); - rootControl.Dock = DockStyle.Fill; - - systemControl = new SystemSolverControl(); - systemControl.Dock = DockStyle.Fill; - - taylorControl = new TaylorSeriesControl(); - taylorControl.Dock = DockStyle.Fill; - - multiTaylorControl = new MultivariableTaylorControl(); - multiTaylorControl.Dock = DockStyle.Fill; - - graphControl = new GraphPlotterControl(); - graphControl.Dock = DockStyle.Fill; + calcControl = new SimpleCalculatorControl { Dock = DockStyle.Fill }; + rootControl = new RootFinderControl { Dock = DockStyle.Fill }; + systemControl = new SystemSolverControl { Dock = DockStyle.Fill }; + matrixControl = new MatrixCalculatorControl { Dock = DockStyle.Fill }; + derivativeControl = new DerivativeCalculatorControl { Dock = DockStyle.Fill }; + taylorControl = new TaylorSeriesControl { Dock = DockStyle.Fill }; + multiTaylorControl = new MultivariableTaylorControl { Dock = DockStyle.Fill }; + combinatoricsControl = new CombinatoricsControl { Dock = DockStyle.Fill }; + graphControl = new GraphPlotterControl { Dock = DockStyle.Fill }; } private void ShowControl(UserControl control) { + pnlContent.SuspendLayout(); pnlContent.Controls.Clear(); pnlContent.Controls.Add(control); + pnlContent.ResumeLayout(); } private void HighlightButton(Button activeBtn) { - Color activeColor = Color.FromArgb(0, 120, 215); // Accent Blue - Color idleColor = Color.FromArgb(40, 40, 40); // Sidebar BG + Color activeColor = ThemeHelper.AccentBlue; + Color idleColor = ThemeHelper.SidebarBackground; - btnNavCalc.BackColor = idleColor; - btnNavRoot.BackColor = idleColor; - btnNavSystem.BackColor = idleColor; - btnNavTaylor.BackColor = idleColor; - btnNavMultiTaylor.BackColor = idleColor; - btnNavGraph.BackColor = idleColor; + Button[] allButtons = { + btnNavCalc, + btnNavRoot, + btnNavSystem, + btnNavMatrix, + btnNavDerivative, + btnNavTaylor, + btnNavMultiTaylor, + btnNavCombinatorics, + btnNavGraph + }; + + foreach (Button b in allButtons) + { + b.BackColor = idleColor; + b.ForeColor = ThemeHelper.MutedText; + b.Font = new Font("Segoe UI", 10F, FontStyle.Regular); + } activeBtn.BackColor = activeColor; + activeBtn.ForeColor = Color.White; + activeBtn.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold); + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + base.OnFormClosing(e); + Environment.Exit(0); } } } diff --git a/MathApp/MathApp/MathApp.Tests/CholeskyDecomposition.cs b/MathApp/MathApp/MathApp.Tests/CholeskyDecomposition.cs index 2f13915..d185d19 100644 --- a/MathApp/MathApp/MathApp.Tests/CholeskyDecomposition.cs +++ b/MathApp/MathApp/MathApp.Tests/CholeskyDecomposition.cs @@ -56,6 +56,7 @@ namespace DotNetMatrix // Main loop. for (int j = 0; j < n; j++) { + if (!isspd) break; decimal[] Lrowj = L[j]; decimal d = 0.0m; for (int k = 0; k < j; k++) @@ -66,13 +67,25 @@ namespace DotNetMatrix { s += Lrowk[i] * Lrowj[i]; } + if (L[k][k] <= 0.0m) + { + isspd = false; + break; + } Lrowj[k] = s = (A[j][k] - s) / L[k][k]; d = d + s * s; isspd = isspd & (A[k][j] == A[j][k]); } + if (!isspd) break; d = A[j][j] - d; isspd = isspd & (d > 0.0m); - L[j][j] = (decimal)Math.Sqrt(Math.Max((double)d, 0)); + if (!isspd || d <= 0.0m) + { + isspd = false; + L[j][j] = 0.0m; + break; + } + L[j][j] = DecimalMath.Sqrt(d); for (int k = j + 1; k < n; k++) { L[j][k] = 0.0m; diff --git a/MathApp/MathApp/MathApp.Tests/DecimalMath.cs b/MathApp/MathApp/MathApp.Tests/DecimalMath.cs index 6c72917..4330fa7 100644 --- a/MathApp/MathApp/MathApp.Tests/DecimalMath.cs +++ b/MathApp/MathApp/MathApp.Tests/DecimalMath.cs @@ -1,26 +1,24 @@ using System; /// -/// Analogy of System.Math class for decimal types +/// Analogy of System.Math class for decimal types with high precision. /// public static class DecimalMath { - /* ... (Content from original file, confirmed no Unity deps) ... */ - /// /// represents PI /// public const decimal PI = 3.14159265358979323846264338327950288419716939937510M; /// - /// represents PI + /// represents machine epsilon for decimal comparisons /// public const decimal Epsilon = 0.0000000000000000001M; /// /// represents 2*PI /// - private const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; + public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M; /// /// represents E @@ -30,12 +28,12 @@ public static class DecimalMath /// /// represents PI/2 /// - private const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; + public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M; /// /// represents PI/4 /// - private const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; + public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M; /// /// represents 1.0/E @@ -68,48 +66,45 @@ public static class DecimalMath private const int MaxIteration = 100; /// - /// Analogy of Math.Exp method + /// Analogy of Math.Exp method with full precision across all ranges /// - /// - /// public static decimal Exp(decimal x) { - var count = 0; - - if (x > One) + if (x == Zero) return One; + if (x > 66.5m) { - count = decimal.ToInt32(decimal.Truncate(x)); - x -= decimal.Truncate(x); + throw new OverflowException("Exp argümanı çok büyük (decimal taşması)."); + } + if (x < -70m) + { + return Zero; } - if (x < Zero) { - count = decimal.ToInt32(decimal.Truncate(x) - 1); - x = One + (x - decimal.Truncate(x)); + return One / Exp(-x); } - var iteration = 1; - var result = One; - var factorial = One; + int count = decimal.ToInt32(decimal.Truncate(x)); + x -= count; + + int iteration = 1; + decimal result = One; + decimal factorial = One; decimal cachedResult; do { cachedResult = result; factorial *= x / iteration++; result += factorial; - } while (cachedResult != result); + } while (cachedResult != result && iteration < MaxIteration); - if (count == 0) - return result; + if (count == 0) return result; return result * PowerN(E, count); } /// /// Analogy of Math.Pow method /// - /// - /// - /// public static decimal Pow(decimal value, decimal pow) { if (pow == Zero) return One; @@ -118,37 +113,32 @@ public static class DecimalMath if (value == Zero) { - if (pow > Zero) - { - return Zero; - } - - throw new Exception("Invalid Operation: zero base and negative power"); + if (pow > Zero) return Zero; + throw new DivideByZeroException("Geçersiz İşlem: Sıfır tabanının negatif kuvveti alınamaz."); } if (pow == -One) return One / value; - var isPowerInteger = IsInteger(pow); + bool isPowerInteger = IsInteger(pow); if (value < Zero && !isPowerInteger) { - throw new Exception("Invalid Operation: negative base and non-integer power"); - } - - if (isPowerInteger && value > Zero) - { - int powerInt = (int)pow; - return PowerN(value, powerInt); - } - - if (isPowerInteger && value < Zero) - { - int powerInt = (int)pow; - if (powerInt % 2 == 0) + // Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5 + decimal invPow = One / pow; + if (IsInteger(invPow)) { - return Exp(pow * Log(-value)); + int q = (int)decimal.Round(invPow); + if (q % 2 != 0) + { + return -Exp(pow * Log(-value)); + } } + throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır."); + } - return -Exp(pow * Log(-value)); + if (isPowerInteger) + { + int powerInt = (int)decimal.Round(pow); + return PowerN(value, powerInt); } return Exp(pow * Log(value)); @@ -156,53 +146,41 @@ public static class DecimalMath private static bool IsInteger(decimal value) { - var longValue = (long)value; - return Abs(value - longValue) <= Epsilon; + var rounded = decimal.Round(value); + return Abs(value - rounded) <= Epsilon; } /// /// Power to the integer value /// - /// - /// - /// public static decimal PowerN(decimal value, int power) { - while (true) + if (power == 0) return One; + if (power < 0) { - if (power == Zero) return One; - if (power < Zero) - { - value = One / value; - power = -power; - continue; - } - - var q = power; - var prod = One; - var current = value; - while (q > 0) - { - if (q % 2 == 1) - { - // detects the 1s in the binary expression of power - prod = current * prod; // picks up the relevant power - q--; - } - - current *= current; // value^i -> value^(2*i) - q >>= 1; - } - - return prod; + value = One / value; + power = -power; } + + int q = power; + decimal prod = One; + decimal current = value; + while (q > 0) + { + if (q % 2 == 1) + { + prod = current * prod; + q--; + } + current *= current; + q >>= 1; + } + return prod; } /// /// Analogy of Math.Log10 /// - /// - /// public static decimal Log10(decimal x) { return Log(x) * Log10Inv; @@ -211,15 +189,13 @@ public static class DecimalMath /// /// Analogy of Math.Log /// - /// - /// public static decimal Log(decimal x) { if (x <= Zero) { - throw new ArgumentException("x must be greater than zero"); + throw new ArgumentException("Logaritma argümanı sıfırdan büyük olmalıdır."); } - var count = 0; + int count = 0; while (x >= One) { x *= Einv; @@ -232,10 +208,11 @@ public static class DecimalMath } x--; if (x == Zero) return count; - var result = Zero; - var iteration = 0; - var y = One; - var cacheResult = result - One; + + decimal result = Zero; + int iteration = 0; + decimal y = One; + decimal cacheResult = result - One; while (cacheResult != result && iteration < MaxIteration) { iteration++; @@ -247,140 +224,127 @@ public static class DecimalMath } /// - /// Analogy of Math.Cos + /// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x) /// - /// - /// - public static decimal Cos(decimal x) + public static decimal Sin(decimal x) { - //truncating to [-2*PI;2*PI] TruncateToPeriodicInterval(ref x); - // now x in (-2pi,2pi) - if (x >= PI && x <= PIx2) - { - return -Cos(x - PI); - } - if (x >= -PIx2 && x <= -PI) - { - return -Cos(x + PI); - } + if (x > PI) x -= PIx2; + else if (x < -PI) x += PIx2; - x *= x; - //y=1-x/2!+x^2/4!-x^3/6!... - var xx = -x * Half; - var y = One + xx; - var cachedY = y - One;//init cache with different value - for (var i = 1; cachedY != y && i < MaxIteration; i++) + if (x > PIdiv2) x = PI - x; + else if (x < -PIdiv2) x = -PI - x; + + decimal x2 = x * x; + decimal term = x; + decimal sum = x; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) { - cachedY = y; - decimal factor = i * ((i << 1) + 3) + 1; //2i^2+2i+i+1=2i^2+3i+1 - factor = -Half / factor; - xx *= x * factor; - y += xx; + cachedSum = sum; + term *= -x2 / ((2 * i) * (2 * i + 1)); + sum += term; + if (sum == cachedSum) break; } - return y; + return sum; + } + + /// + /// Analogy of Math.Cos + /// + public static decimal Cos(decimal x) + { + TruncateToPeriodicInterval(ref x); + + if (x > PI) x -= PIx2; + else if (x < -PI) x += PIx2; + + if (x > PIdiv2) return -Cos(PI - x); + if (x < -PIdiv2) return -Cos(-PI - x); + + decimal x2 = x * x; + decimal term = One; + decimal sum = One; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) + { + cachedSum = sum; + term *= -x2 / ((2 * i - 1) * (2 * i)); + sum += term; + if (sum == cachedSum) break; + } + return sum; } /// /// Analogy of Math.Tan /// - /// - /// public static decimal Tan(decimal x) { - var cos = Cos(x); - if (cos == Zero) throw new ArgumentException(nameof(x)); - //calculate sin using cos - var sin = CalculateSinFromCos(x, cos); - return sin / cos; - } - /// - /// Helper function for calculating sin(x) from cos(x) - /// - /// - /// - /// - private static decimal CalculateSinFromCos(decimal x, decimal cos) - { - var moduleOfSin = Sqrt(One - (cos * cos)); - var sineIsPositive = IsSignOfSinePositive(x); - if (sineIsPositive) return moduleOfSin; - return -moduleOfSin; - } - /// - /// Analogy of Math.Sin - /// - /// - /// - public static decimal Sin(decimal x) - { - var cos = Cos(x); - return CalculateSinFromCos(x, cos); + decimal cos = Cos(x); + if (Abs(cos) <= 1e-25m) throw new ArgumentException("Tan(x) bu noktada tanımsızdır (cos(x) = 0)."); + return Sin(x) / cos; } - - /// - /// Truncates to [-2*PI;2*PI] - /// - /// private static void TruncateToPeriodicInterval(ref decimal x) { - while (x >= PIx2) + if (x >= PIx2 || x <= -PIx2) { - var divide = Math.Abs(decimal.ToInt32(x / PIx2)); - x -= divide * PIx2; + x = x % PIx2; } - - while (x <= -PIx2) - { - var divide = Math.Abs(decimal.ToInt32(x / PIx2)); - x += divide * PIx2; - } - } - - - private static bool IsSignOfSinePositive(decimal x) - { - //truncating to [-2*PI;2*PI] - TruncateToPeriodicInterval(ref x); - - //now x in [-2*PI;2*PI] - if (x >= -PIx2 && x <= -PI) return true; - if (x >= -PI && x <= Zero) return false; - if (x >= Zero && x <= PI) return true; - if (x >= PI && x <= PIx2) return false; - - //will not be reached - throw new ArgumentException(nameof(x)); } /// - /// Analogy of Math.Sqrt + /// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation) /// - /// - /// lasts iteration while error less than this epsilon - /// public static decimal Sqrt(decimal x, decimal epsilon = Zero) { - if (x < Zero) throw new OverflowException("Cannot calculate square root from a negative number"); - //initial approximation - decimal current = (decimal)Math.Sqrt((double)x), previous; - do + if (x < Zero) throw new ArgumentException("Negatif sayının karekökü reel sayılarda alınamaz."); + if (x == Zero) return Zero; + + decimal current = (decimal)Math.Sqrt((double)x); + if (current == Zero) current = x * Half; + + decimal previous = Zero; + int maxSteps = 25; + for (int step = 0; step < maxSteps; step++) { + decimal next = (current + x / current) * Half; + if (next == current || next == previous || Abs(next - current) <= epsilon) + { + return next; + } previous = current; - if (previous == Zero) return Zero; - current = (previous + x / previous) * Half; - } while (Abs(previous - current) > epsilon); + current = next; + } return current; } + /// /// Analogy of Math.Sinh /// - /// - /// public static decimal Sinh(decimal x) { + if (x < Zero) return -Sinh(-x); + + if (Abs(x) < 0.1m) + { + // Taylor series for small x to avoid loss of significance in (e^x - e^-x)/2 + decimal x2 = x * x; + decimal term = x; + decimal sum = x; + decimal cachedSum; + for (int i = 1; i < MaxIteration; i++) + { + cachedSum = sum; + term *= x2 / ((2 * i) * (2 * i + 1)); + sum += term; + if (sum == cachedSum) break; + } + return sum; + } + var y = Exp(x); var yy = One / y; return (y - yy) * Half; @@ -389,10 +353,9 @@ public static class DecimalMath /// /// Analogy of Math.Cosh /// - /// - /// public static decimal Cosh(decimal x) { + if (x < Zero) x = -x; var y = Exp(x); var yy = One / y; return (y + yy) * Half; @@ -401,8 +364,6 @@ public static class DecimalMath /// /// Analogy of Math.Sign /// - /// - /// public static int Sign(decimal x) { return x < Zero ? -1 : (x > Zero ? 1 : 0); @@ -411,109 +372,103 @@ public static class DecimalMath /// /// Analogy of Math.Tanh /// - /// - /// public static decimal Tanh(decimal x) { - var y = Exp(x); - var yy = One / y; - return (y - yy) / (y + yy); + if (x > 35m) return One; + if (x < -35m) return -One; + + var y = Exp(2m * x); + return (y - One) / (y + One); } /// /// Analogy of Math.Abs /// - /// - /// public static decimal Abs(decimal x) { - if (x <= Zero) - { - return -x; - } - return x; + return x <= Zero ? -x : x; } /// /// Analogy of Math.Asin /// - /// - /// public static decimal Asin(decimal x) { if (x > One || x < -One) { - throw new ArgumentException("x must be in [-1,1]"); + throw new ArgumentException("Asin argümanı [-1, 1] aralığında olmalıdır."); } - //known values if (x == Zero) return Zero; if (x == One) return PIdiv2; - //asin function is odd function + if (x == -One) return -PIdiv2; if (x < Zero) return -Asin(-x); - //my optimize trick here - - // used a math formula to speed up : - // asin(x)=0.5*(pi/2-asin(1-2*x*x)) - // if x>=0 is true - var newX = One - 2 * x * x; - - //for calculating new value near to zero than current - //because we gain more speed with values near to zero if (Abs(x) > Abs(newX)) { var t = Asin(newX); return Half * (PIdiv2 - t); } - var y = Zero; - var result = x; + + decimal y = Zero; + decimal result = x; decimal cachedResult; - var i = 1; + int i = 1; y += result; - var xx = x * x; + decimal xx = x * x; do { cachedResult = result; - result *= xx * (One - Half / (i)); + result *= xx * (One - Half / i); y += result / ((i << 1) + 1); i++; - } while (cachedResult != result); + } while (cachedResult != result && i < MaxIteration); return y; } /// - /// Analogy of Math.Atan + /// Analogy of Math.Atan (safe against overflow for large x) /// - /// - /// public static decimal Atan(decimal x) { if (x == Zero) return Zero; if (x == One) return PIdiv4; + if (x == -One) return -PIdiv4; + + if (x > 100000000000000m) return PIdiv2; + if (x < -100000000000000m) return -PIdiv2; + + if (x > One) + { + return PIdiv2 - Atan(One / x); + } + if (x < -One) + { + return -PIdiv2 - Atan(One / x); + } + return Asin(x / Sqrt(One + x * x)); } + /// /// Analogy of Math.Acos /// - /// - /// public static decimal Acos(decimal x) { + if (x > One || x < -One) + { + throw new ArgumentException("Acos argümanı [-1, 1] aralığında olmalıdır."); + } if (x == Zero) return PIdiv2; if (x == One) return Zero; + if (x == -One) return PI; if (x < Zero) return PI - Acos(-x); return PIdiv2 - Asin(x); } /// /// Analogy of Math.Atan2 - /// for more see this - /// /// - /// - /// - /// public static decimal Atan2(decimal y, decimal x) { if (x > Zero) @@ -536,6 +491,6 @@ public static class DecimalMath { return -PIdiv2; } - throw new ArgumentException("invalid atan2 arguments"); + throw new ArgumentException("Geçersiz Atan2 argümanları (0, 0)."); } } diff --git a/MathApp/MathApp/MathApp.Tests/EigenvalueDecomposition.cs b/MathApp/MathApp/MathApp.Tests/EigenvalueDecomposition.cs index 9a8a49b..3cf03a8 100644 --- a/MathApp/MathApp/MathApp.Tests/EigenvalueDecomposition.cs +++ b/MathApp/MathApp/MathApp.Tests/EigenvalueDecomposition.cs @@ -146,7 +146,7 @@ namespace DotNetMatrix decimal f = 0.0m; decimal tst1 = 0.0m; - decimal eps = (decimal)DecimalMath.Pow(2.0m, - 52.0m); + decimal eps = DecimalMath.Pow(2.0m, -64.0m); for (int l = 0; l < n; l++) { tst1 = System.Math.Max(tst1, System.Math.Abs(d[l]) + System.Math.Abs(e[l])); @@ -166,6 +166,7 @@ namespace DotNetMatrix do { iter = iter + 1; + if (iter > 120) break; decimal g = d[l]; decimal p = (d[l + 1] - g) / (2.0m * e[l]); decimal r = Maths.Hypot(p, 1.0m); @@ -388,8 +389,10 @@ namespace DotNetMatrix } int iter = 0; - while (n >= low) + int totalIter = 0; + while (n >= low && totalIter < 400) { + totalIter++; int l = n; while (l > low) { @@ -702,7 +705,7 @@ namespace DotNetMatrix } t = System.Math.Abs(H[i][n]); - if ((eps * t) * t > 1) + if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) { for (int j = i; j <= n; j++) { @@ -782,7 +785,7 @@ namespace DotNetMatrix } t = System.Math.Max(System.Math.Abs(H[i][n - 1]), System.Math.Abs(H[i][n])); - if ((eps * t) * t > 1) + if (t > 0 && (t > 1000000000000m || (eps * t) > 1m / t)) { for (int j = i; j <= n; j++) { diff --git a/MathApp/MathApp/MathApp.Tests/Function.cs b/MathApp/MathApp/MathApp.Tests/Function.cs index 899dc1d..26d7ff8 100644 --- a/MathApp/MathApp/MathApp.Tests/Function.cs +++ b/MathApp/MathApp/MathApp.Tests/Function.cs @@ -1,71 +1,47 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Globalization; - -/// -/// -/// public enum Type { Variable, Value, UnaryOperator, Operator, Function, Result, Bracket, Comma, Error } + public struct Symbol { public string m_name; public decimal m_value; public Type m_type; + public int m_argCount; public override string ToString() { return m_name; } } -public delegate Symbol EvaluateFunctionDelegate(string name, params Object[] args); + +public delegate Symbol EvaluateFunctionDelegate(string name, params Symbol[] args); + public class Function { - public decimal Result + private static readonly HashSet KnownFunctions = new HashSet(StringComparer.OrdinalIgnoreCase) { - get - { - return m_result; - } - } + "sin", "cos", "tan", "cot", "cosh", "sinh", "tanh", + "log", "ln", "logn", "sqrt", "cbrt", "abs", + "acos", "asin", "atan", "atan2", "exp", + "max", "min", "floor", "ceil", "round", "sign" + }; - public ArrayList Equation - { - get - { - return (ArrayList)m_equation.Clone(); - } - } - public ArrayList Postfix - { - get - { - return (ArrayList)m_postfix.Clone(); - } - } + public static bool UseRadians { get; set; } = true; + + public decimal Result => m_result; + public ArrayList Equation => (ArrayList)m_equation.Clone(); + public ArrayList Postfix => (ArrayList)m_postfix.Clone(); public EvaluateFunctionDelegate DefaultFunctionEvaluation { - set - { - m_defaultFunctionEvaluation = value; - } + set => m_defaultFunctionEvaluation = value; } - public bool Error - { - get - { - return m_bError; - } - } - - public string ErrorDescription - { - get - { - return m_sErrorDescription; - } - } + public bool Error => m_bError; + public string ErrorDescription => m_sErrorDescription; public ArrayList Variables { @@ -96,14 +72,69 @@ public class Function } } + public void SetVariable(string name, decimal value) + { + for (int i = 0; i < m_postfix.Count; i++) + { + Symbol s = (Symbol)m_postfix[i]; + if (s.m_type == Type.Variable && string.Equals(s.m_name, name, StringComparison.OrdinalIgnoreCase)) + { + s.m_value = value; + m_postfix[i] = s; + } + } + } + + public void SetVariables(Dictionary values) + { + for (int i = 0; i < m_postfix.Count; i++) + { + Symbol s = (Symbol)m_postfix[i]; + if (s.m_type == Type.Variable && values.TryGetValue(s.m_name, out decimal val)) + { + s.m_value = val; + m_postfix[i] = s; + } + } + } + public Function() - { } + { + } + + private void AddSymbolWithImplicitMultiplication(Symbol sym) + { + if (m_equation.Count > 0) + { + Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; + bool prevIsOperandOrClose = prev.m_type == Type.Value || + prev.m_type == Type.Variable || + prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}"; + + bool currIsOperandOrOpen = sym.m_type == Type.Value || + sym.m_type == Type.Variable || + sym.m_type == Type.Function || + sym.m_name == "(" || sym.m_name == "[" || sym.m_name == "{"; + + if (prevIsOperandOrClose && currIsOperandOrOpen) + { + Symbol mulSym = new Symbol + { + m_name = "*", + m_value = 0, + m_type = Type.Operator + }; + m_equation.Add(mulSym); + } + } + m_equation.Add(sym); + } public void Parse(string equation) { int state = 1; string temp = ""; - Symbol ctSymbol = new Symbol(); // Initialized to avoid error + Symbol ctSymbol = new Symbol(); m_bError = false; m_sErrorDescription = "None"; @@ -111,179 +142,252 @@ public class Function m_equation.Clear(); m_postfix.Clear(); - int nPos = 0; - //-- Remove all white spaces from the equation string -- - equation = equation.Trim(); - while ((nPos = equation.IndexOf(' ')) != -1) - equation = equation.Remove(nPos, 1); + if (string.IsNullOrWhiteSpace(equation)) + { + m_bError = true; + m_sErrorDescription = "Denklem boş olamaz."; + return; + } + // We process whitespace as delimiter without deleting it globally for (int i = 0; i < equation.Length; i++) { + char ch = equation[i]; switch (state) { - case 1: - if (Char.IsNumber(equation[i])) + case 1: // Neutral + if (char.IsWhiteSpace(ch)) + { + continue; + } + if (char.IsDigit(ch) || ch == '.') { state = 2; - temp += equation[i]; + temp += ch; } - else if (Char.IsLetter(equation[i])) + else if (char.IsLetter(ch)) { state = 3; - temp += equation[i]; + temp += ch; } else { - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) - { - case ",": - case ".": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; - break; - } - m_equation.Add(ctSymbol); + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } break; - case 2: - if ((Char.IsNumber(equation[i])) || (equation[i] == '.') || (equation[i] == ',')) - temp += equation[i]; - else if (!Char.IsLetter(equation[i])) + + case 2: // Reading Number + if (char.IsDigit(ch) || ch == '.') { - state = 1; - ctSymbol.m_name = temp; - ctSymbol.m_value = Decimal.Parse(temp, System.Globalization.CultureInfo.InvariantCulture); - ctSymbol.m_type = Type.Value; - m_equation.Add(ctSymbol); - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) - { - case ",": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; - break; - } - m_equation.Add(ctSymbol); + temp += ch; + } + else if (char.IsWhiteSpace(ch)) + { + if (!EmitNumberSymbol(temp)) return; temp = ""; + state = 1; } - break; - case 3: - if (Char.IsLetterOrDigit(equation[i])) - temp += equation[i]; else { - state = 1; - ctSymbol.m_name = temp; - ctSymbol.m_value = 0; - if (equation[i] == '(') - ctSymbol.m_type = Type.Function; + if (!EmitNumberSymbol(temp)) return; + temp = ""; + + if (char.IsLetter(ch)) + { + state = 3; + temp += ch; + } else { - if (ctSymbol.m_name == "pi") - ctSymbol.m_value = DecimalMath.PI; - else if (ctSymbol.m_name == "e") - ctSymbol.m_value = DecimalMath.E; - ctSymbol.m_type = Type.Variable; + state = 1; + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } - m_equation.Add(ctSymbol); - ctSymbol.m_name = equation[i].ToString(); - ctSymbol.m_value = 0; - switch (ctSymbol.m_name) + } + break; + + case 3: // Reading Identifier + if (char.IsLetterOrDigit(ch)) + { + temp += ch; + } + else if (char.IsWhiteSpace(ch)) + { + // Lookahead to see if next non-whitespace is '(' + bool nextIsOpen = false; + for (int k = i + 1; k < equation.Length; k++) { - case ",": - ctSymbol.m_type = Type.Comma; - break; - case "(": - case ")": - case "[": - case "]": - case "{": - case "}": - ctSymbol.m_type = Type.Bracket; - break; - default: - if (m_equation.Count == 0) - ctSymbol.m_type = Type.UnaryOperator; - else if ((((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Value) || (((Symbol)m_equation[m_equation.Count - 1]).m_type == Type.Variable) - || (((Symbol)m_equation[m_equation.Count - 1]).m_name == ")") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "]") || (((Symbol)m_equation[m_equation.Count - 1]).m_name == "}")) - ctSymbol.m_type = Type.Operator; - else - ctSymbol.m_type = Type.UnaryOperator; + if (!char.IsWhiteSpace(equation[k])) + { + nextIsOpen = (equation[k] == '(' || equation[k] == '[' || equation[k] == '{'); break; + } } - m_equation.Add(ctSymbol); + EmitIdentifierSymbol(temp, nextIsOpen); temp = ""; + state = 1; + } + else + { + state = 1; + EmitIdentifierSymbol(temp, ch == '(' || ch == '[' || ch == '{'); + temp = ""; + + ctSymbol = ClassifyNonAlphanumeric(ch.ToString()); + AddSymbolWithImplicitMultiplication(ctSymbol); } break; } } + if (temp != "") { - ctSymbol.m_name = temp; if (state == 2) { - ctSymbol.m_value = Decimal.Parse(temp, System.Globalization.CultureInfo.InvariantCulture); - ctSymbol.m_type = Type.Value; + if (!EmitNumberSymbol(temp)) return; } else { - if (ctSymbol.m_name == "pi") - ctSymbol.m_value = DecimalMath.PI; - else if (ctSymbol.m_name == "e") - ctSymbol.m_value = DecimalMath.E; - else - ctSymbol.m_value = 0; - ctSymbol.m_type = Type.Variable; + EmitIdentifierSymbol(temp, false); } - m_equation.Add(ctSymbol); } } + private bool EmitNumberSymbol(string temp) + { + if (!decimal.TryParse(temp, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val)) + { + m_bError = true; + m_sErrorDescription = "Geçersiz sayı formatı: " + temp; + return false; + } + + Symbol sym = new Symbol + { + m_name = temp, + m_value = val, + m_type = Type.Value + }; + AddSymbolWithImplicitMultiplication(sym); + return true; + } + + private void EmitIdentifierSymbol(string temp, bool isNextOpenParen) + { + Symbol sym = new Symbol + { + m_name = temp, + m_value = 0 + }; + + string lower = temp.ToLowerInvariant(); + if (lower == "pi") + { + sym.m_value = DecimalMath.PI; + sym.m_type = Type.Value; + } + else if (lower == "e") + { + sym.m_value = DecimalMath.E; + sym.m_type = Type.Value; + } + else if (isNextOpenParen) + { + if (temp.Length == 1 && (temp == "x" || temp == "y" || temp == "z" || temp == "t" || temp == "u" || temp == "v")) + { + sym.m_type = Type.Variable; + } + else + { + sym.m_type = Type.Function; + } + } + else + { + sym.m_type = Type.Variable; + } + AddSymbolWithImplicitMultiplication(sym); + } + + private Symbol ClassifyNonAlphanumeric(string token) + { + Symbol ctSymbol = new Symbol + { + m_name = token, + m_value = 0 + }; + + switch (token) + { + case ",": + case ";": + ctSymbol.m_type = Type.Comma; + break; + case "(": + case ")": + case "[": + case "]": + case "{": + case "}": + ctSymbol.m_type = Type.Bracket; + break; + default: + if (m_equation.Count == 0) + { + ctSymbol.m_type = Type.UnaryOperator; + } + else + { + Symbol prev = (Symbol)m_equation[m_equation.Count - 1]; + if (prev.m_type == Type.Value || prev.m_type == Type.Variable || + prev.m_name == ")" || prev.m_name == "]" || prev.m_name == "}") + { + ctSymbol.m_type = Type.Operator; + } + else + { + ctSymbol.m_type = Type.UnaryOperator; + } + } + break; + } + return ctSymbol; + } + public void Infix2Postfix() { + m_postfix.Clear(); Symbol tpSym; Stack tpStack = new Stack(); + Stack fnArgCounts = new Stack(); + foreach (Symbol sym in m_equation) { if ((sym.m_type == Type.Value) || (sym.m_type == Type.Variable)) m_postfix.Add(sym); + else if (sym.m_type == Type.Function) + { + tpStack.Push(sym); + fnArgCounts.Push(1); + } else if ((sym.m_name == "(") || (sym.m_name == "[") || (sym.m_name == "{")) tpStack.Push(sym); + else if (sym.m_type == Type.Comma) + { + while (tpStack.Count > 0) + { + tpSym = (Symbol)tpStack.Peek(); + if (tpSym.m_name == "(" || tpSym.m_name == "[" || tpSym.m_name == "{") + break; + m_postfix.Add(tpStack.Pop()); + } + if (fnArgCounts.Count > 0) + { + int c = fnArgCounts.Pop(); + fnArgCounts.Push(c + 1); + } + } else if ((sym.m_name == ")") || (sym.m_name == "]") || (sym.m_name == "}")) { if (tpStack.Count > 0) @@ -292,28 +396,56 @@ public class Function while ((tpSym.m_name != "(") && (tpSym.m_name != "[") && (tpSym.m_name != "{")) { m_postfix.Add(tpSym); + if (tpStack.Count == 0) break; tpSym = (Symbol)tpStack.Pop(); } + + if (tpStack.Count > 0 && ((Symbol)tpStack.Peek()).m_type == Type.Function) + { + Symbol fn = (Symbol)tpStack.Pop(); + fn.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; + m_postfix.Add(fn); + } } } else if (sym.m_type == Type.UnaryOperator) { + // Unary operators (like unary - or +) modify the operand to their right. + // They should never pop binary operators (^, *, /, +, -) from the stack. + tpStack.Push(sym); + } + else if (sym.m_name == "^") + { + // Right-associative operator ^ + while (tpStack.Count > 0) + { + tpSym = (Symbol)tpStack.Peek(); + if ((tpSym.m_type == Type.Operator || tpSym.m_type == Type.Function) && + Precedence(tpSym) > Precedence(sym)) + { + m_postfix.Add(tpStack.Pop()); + } + else + { + break; + } + } tpStack.Push(sym); } else { - if (tpStack.Count > 0) + while (tpStack.Count > 0) { - tpSym = (Symbol)tpStack.Pop(); - while ((tpStack.Count != 0) && ((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym))) + tpSym = (Symbol)tpStack.Peek(); + if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function)) && + (Precedence(tpSym) >= Precedence(sym))) { - m_postfix.Add(tpSym); - tpSym = (Symbol)tpStack.Pop(); + m_postfix.Add(tpStack.Pop()); } - if (((tpSym.m_type == Type.UnaryOperator) || (tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym))) - m_postfix.Add(tpSym); else - tpStack.Push(tpSym); + { + break; + } } tpStack.Push(sym); } @@ -321,6 +453,10 @@ public class Function while (tpStack.Count > 0) { tpSym = (Symbol)tpStack.Pop(); + if (tpSym.m_type == Type.Function && tpSym.m_argCount == 0) + { + tpSym.m_argCount = fnArgCounts.Count > 0 ? fnArgCounts.Pop() : 1; + } m_postfix.Add(tpSym); } } @@ -329,7 +465,6 @@ public class Function { Symbol tpSym1, tpSym2, tpResult; Stack tpStack = new Stack(); - ArrayList fnParam = new ArrayList(); m_bError = false; foreach (Symbol sym in m_postfix) { @@ -337,6 +472,12 @@ public class Function tpStack.Push(sym); else if (sym.m_type == Type.UnaryOperator) { + if (tpStack.Count < 1) + { + m_bError = true; + m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; + return; + } tpSym1 = (Symbol)tpStack.Pop(); tpResult = Evaluate(sym, tpSym1); if (tpResult.m_type == Type.Error) @@ -349,6 +490,12 @@ public class Function } else if (sym.m_type == Type.Operator) { + if (tpStack.Count < 2) + { + m_bError = true; + m_sErrorDescription = "Sözdizimi hatası (eksik operand)."; + return; + } tpSym1 = (Symbol)tpStack.Pop(); tpSym2 = (Symbol)tpStack.Pop(); tpResult = Evaluate(tpSym2, sym, tpSym1); @@ -360,55 +507,30 @@ public class Function } tpStack.Push(tpResult); } - else if (sym.m_type == Type.Comma) - { - tpStack.Push(sym); - } else if (sym.m_type == Type.Function) { - fnParam.Clear(); - tpSym1 = (Symbol)tpStack.Pop(); - if ((tpSym1.m_type == Type.Value) || (tpSym1.m_type == Type.Variable) || (tpSym1.m_type == Type.Result)) + int count = sym.m_argCount > 0 ? sym.m_argCount : 1; + if (tpStack.Count < count) { - tpResult = EvaluateFunction(sym.m_name, tpSym1); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + m_bError = true; + m_sErrorDescription = $"Fonksiyon '{sym.m_name}' için argüman eksik."; + return; } - else if (tpSym1.m_type == Type.Comma) + + Symbol[] fnParam = new Symbol[count]; + for (int i = count - 1; i >= 0; i--) { - while (tpSym1.m_type == Type.Comma) - { - tpSym1 = (Symbol)tpStack.Pop(); - fnParam.Add(tpSym1); - tpSym1 = (Symbol)tpStack.Pop(); - } - fnParam.Add(tpSym1); - tpResult = EvaluateFunction(sym.m_name, fnParam.ToArray()); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + fnParam[i] = (Symbol)tpStack.Pop(); } - else + + tpResult = EvaluateFunction(sym.m_name, fnParam); + if (tpResult.m_type == Type.Error) { - tpStack.Push(tpSym1); - tpResult = EvaluateFunction(sym.m_name); - if (tpResult.m_type == Type.Error) - { - m_bError = true; - m_sErrorDescription = tpResult.m_name; - return; - } - tpStack.Push(tpResult); + m_bError = true; + m_sErrorDescription = tpResult.m_name; + return; } + tpStack.Push(tpResult); } } if (tpStack.Count == 1) @@ -416,6 +538,11 @@ public class Function tpResult = (Symbol)tpStack.Pop(); m_result = tpResult.m_value; } + else if (tpStack.Count > 1) + { + m_bError = true; + m_sErrorDescription = "İfade tam çözümlenemedi (fazla terim)."; + } } protected int Precedence(Symbol sym) @@ -425,16 +552,16 @@ public class Function case Type.Bracket: return 7; case Type.Function: - return 5; + return 6; case Type.UnaryOperator: - return 4; + return 3; case Type.Comma: return 0; } switch (sym.m_name) { case "^": - return 3; + return 5; case "/": case "*": case "%": @@ -448,21 +575,21 @@ public class Function protected Symbol Evaluate(Symbol opr, Symbol sym1) { - Symbol result; + Symbol result = default; result.m_name = opr.m_name + sym1.m_name; result.m_type = Type.Result; result.m_value = 0; switch (opr.m_name) { case "+": - result.m_value = sym1.m_value; ; + result.m_value = sym1.m_value; break; case "-": result.m_value = -1 * sym1.m_value; break; default: result.m_type = Type.Error; - result.m_name = "Undefine unary operator: " + opr.m_name + "."; + result.m_name = "Tanımsız tekli operatör: " + opr.m_name; break; } return result; @@ -470,244 +597,390 @@ public class Function protected Symbol Evaluate(Symbol sym1, Symbol opr, Symbol sym2) { - Symbol result; + Symbol result = default; result.m_name = sym1.m_name + opr.m_name + sym2.m_name; result.m_type = Type.Result; result.m_value = 0; - switch (opr.m_name) + try { - case "^": - result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); - break; - case "/": - { + switch (opr.m_name) + { + case "^": + result.m_value = DecimalMath.Pow(sym1.m_value, sym2.m_value); + break; + case "/": if (sym2.m_value != 0) result.m_value = sym1.m_value / sym2.m_value; else { - result.m_name = "Divide by Zero."; + result.m_name = "Sıfıra bölme hatası (Divide by Zero)."; result.m_type = Type.Error; } break; - } - case "*": - result.m_value = sym1.m_value * sym2.m_value; - break; - case "%": - result.m_value = sym1.m_value % sym2.m_value; - break; - case "+": - result.m_value = sym1.m_value + sym2.m_value; - break; - case "-": - result.m_value = sym1.m_value - sym2.m_value; - break; - default: - result.m_type = Type.Error; - result.m_name = "Undefine operator: " + opr.m_name + "."; - break; + case "*": + result.m_value = sym1.m_value * sym2.m_value; + break; + case "%": + if (sym2.m_value != 0) + result.m_value = sym1.m_value % sym2.m_value; + else + { + result.m_name = "Sıfıra göre mod alınamaz."; + result.m_type = Type.Error; + } + break; + case "+": + result.m_value = sym1.m_value + sym2.m_value; + break; + case "-": + result.m_value = sym1.m_value - sym2.m_value; + break; + default: + result.m_type = Type.Error; + result.m_name = "Tanımsız operatör: " + opr.m_name; + break; + } + } + catch (Exception ex) + { + result.m_type = Type.Error; + result.m_name = ex.Message; } return result; } - protected Symbol EvaluateFunction(string name, params Object[] args) + protected Symbol EvaluateFunction(string name, params Symbol[] args) { - Symbol result; + Symbol result = default; result.m_name = ""; result.m_type = Type.Result; result.m_value = 0; - switch (name) + + string lowerName = name.ToLowerInvariant(); + decimal angleFactor = UseRadians ? 1.0m : (DecimalMath.PI / 180.0m); + decimal invAngleFactor = UseRadians ? 1.0m : (180.0m / DecimalMath.PI); + + try { - case "cos": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Cos(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sin": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sin(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "tan": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Tan(((Symbol)args[0]).m_value * DecimalMath.PI / 180); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "cosh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Cosh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sinh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sinh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "tanh": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Tanh(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "log": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log10(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "ln": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Log(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "logn": - if (args.Length == 2) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + "'" + ((Symbol)args[1]).m_value.ToString() + ")"; - // log_b(x) = ln(x) / ln(b) - result.m_value = DecimalMath.Log(((Symbol)args[0]).m_value) / DecimalMath.Log(((Symbol)args[1]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "sqrt": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Sqrt(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "abs": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Abs(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "acos": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Acos(((Symbol)args[0]).m_value) * 180 / DecimalMath.PI; - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "asin": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Asin(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "atan": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Atan(((Symbol)args[0]).m_value) * 180 / DecimalMath.PI; - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - case "exp": - if (args.Length == 1) - { - result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")"; - result.m_value = DecimalMath.Exp(((Symbol)args[0]).m_value); - } - else - { - result.m_name = "Invalid number of parameters in: " + name + "."; - result.m_type = Type.Error; - } - break; - default: - if (m_defaultFunctionEvaluation != null) - result = m_defaultFunctionEvaluation(name, args); - else - { - result.m_name = "Function: " + name + ", not found."; - result.m_type = Type.Error; - } - break; + switch (lowerName) + { + case "cos": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Cos(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sin": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sin(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "tan": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Tan(v * angleFactor); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cot": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + decimal sinVal = DecimalMath.Sin(v * angleFactor); + if (DecimalMath.Abs(sinVal) <= 1e-25m) + { + result.m_name = "Cot(x) bu noktada tanımsızdır (sin(x) = 0)."; + result.m_type = Type.Error; + } + else + { + result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal; + } + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cosh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Cosh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sinh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sinh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "tanh": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Tanh(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "log": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log10(v); + } + else if (args.Length == 2) + { + decimal v = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "ln": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "logn": + if (args.Length == 2) + { + decimal v = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + "," + b.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Log(v) / DecimalMath.Log(b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "sqrt": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Sqrt(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "cbrt": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = v < 0 ? -DecimalMath.Pow(-v, 1m / 3m) : DecimalMath.Pow(v, 1m / 3m); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "abs": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Abs(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "acos": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Acos(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "asin": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Asin(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "atan": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Atan(v) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "atan2": + if (args.Length == 2) + { + decimal y = ((Symbol)args[0]).m_value; + decimal x = ((Symbol)args[1]).m_value; + result.m_name = name + "(" + y.ToString(CultureInfo.InvariantCulture) + "," + x.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Atan2(y, x) * invAngleFactor; + } + else + { + result.m_name = "Geçersiz parametre sayısı: atan2(y, x)"; + result.m_type = Type.Error; + } + break; + case "exp": + if (args.Length == 1) + { + decimal v = ((Symbol)args[0]).m_value; + result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; + result.m_value = DecimalMath.Exp(v); + } + else + { + result.m_name = "Geçersiz parametre sayısı: " + name; + result.m_type = Type.Error; + } + break; + case "max": + if (args.Length == 2) + { + decimal a = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_value = Math.Max(a, b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: max(a, b)"; + result.m_type = Type.Error; + } + break; + case "min": + if (args.Length == 2) + { + decimal a = ((Symbol)args[0]).m_value; + decimal b = ((Symbol)args[1]).m_value; + result.m_value = Math.Min(a, b); + } + else + { + result.m_name = "Geçersiz parametre sayısı: min(a, b)"; + result.m_type = Type.Error; + } + break; + case "floor": + if (args.Length == 1) + { + result.m_value = decimal.Floor(((Symbol)args[0]).m_value); + } + break; + case "ceil": + if (args.Length == 1) + { + result.m_value = decimal.Ceiling(((Symbol)args[0]).m_value); + } + break; + case "round": + if (args.Length == 1) + { + result.m_value = decimal.Round(((Symbol)args[0]).m_value); + } + break; + case "sign": + if (args.Length == 1) + { + result.m_value = DecimalMath.Sign(((Symbol)args[0]).m_value); + } + break; + default: + if (m_defaultFunctionEvaluation != null) + result = m_defaultFunctionEvaluation(name, args); + else + { + result.m_name = "Fonksiyon bulunamadı: " + name; + result.m_type = Type.Error; + } + break; + } + } + catch (Exception ex) + { + result.m_name = ex.Message; + result.m_type = Type.Error; } return result; } diff --git a/MathApp/MathApp/MathApp.Tests/Matrix.cs b/MathApp/MathApp/MathApp.Tests/Matrix.cs index 3b32f59..ab84f5e 100644 --- a/MathApp/MathApp/MathApp.Tests/Matrix.cs +++ b/MathApp/MathApp/MathApp.Tests/Matrix.cs @@ -2,6 +2,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; +using DotNetMatrix; public class Matrix { @@ -15,7 +16,6 @@ public class Matrix res[i] = new decimal[columns]; for (int j = 0; j < columns; j++) { - // Replaced UnityEngine.Random with System.Random double range = (double)(max - min); double sample = random.NextDouble(); double scaled = (sample * range) + (double)min; @@ -28,6 +28,7 @@ public class Matrix public static decimal[][] Transpoze(decimal[][] _m) { + if (_m == null || _m.Length == 0) return new decimal[0][]; decimal[][] res = new decimal[_m[0].Length][]; for (int i = 0; i < _m[0].Length; i++) { @@ -45,162 +46,81 @@ public class Matrix public static decimal MatrixDeterminant(decimal[][] _m) { - if (_m.Length == _m[0].Length) + if (_m == null || _m.Length == 0) return 0; + if (_m.Length != _m[0].Length) { - int c = _m.Length; - if (c == 2) - { - return (decimal)Math.Round(_m[0][0] * _m[1][1] - _m[0][1] * _m[1][0], 5); - } - else if (c == 1) - { - return (decimal)Math.Round(_m[0][0], 5); - } - else if (c == 0) - { - Console.WriteLine("Matrix is empty!"); - return 0; - } - else - { - decimal resDet = 0; - for (int i = 0; i < c; i++) - { - for (int j = 0; j < c; j++) - { - decimal[][] newM = new decimal[c - 1][]; - for (int k = 0; k < c - 1; k++) - { - newM[k] = new decimal[c - 1]; - } - - bool isAddedK = false, isAddedL = false; - int offsetK = 0, offsetL = 0; - - for (int k = 0; k < c; k++) - { - isAddedL = false; - offsetL = 0; - for (int l = 0; l < c; l++) - { - if (!(k == i || l == j)) - { - newM[k + offsetK][l + offsetL] = _m[k][l]; - } - else - { - if (!isAddedK && k == i) - { - offsetK = -1; - isAddedK = true; - } - if (!isAddedL && l == j) - { - offsetL = -1; - isAddedL = true; - } - } - } - } - - decimal cofactor = (decimal)Math.Pow(-1, 0 + j + 2) * MatrixDeterminant(newM); - resDet += cofactor * _m[0][j]; - } - } - return (decimal)Math.Round(resDet, 5); - } - } - else - { - Console.WriteLine("This matrix is not a square matrix!"); - return 0; + throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır."); } + + int n = _m.Length; + if (n == 1) return _m[0][0]; + if (n == 2) return _m[0][0] * _m[1][1] - _m[0][1] * _m[1][0]; + + // Use O(n^3) LU Decomposition instead of O(n!) recursive Laplace expansion + GeneralMatrix gm = GeneralMatrix.ConstructWithCopy(_m); + return gm.Determinant(); } public static decimal[] SolveEquation(decimal[][] _m, decimal[] _v) { + if (_m == null || _v == null || _m.Length == 0) return new decimal[0]; int len = _m.Length; - decimal[] res = new decimal[len]; - decimal d0 = MatrixDeterminant(_m); - + GeneralMatrix A = GeneralMatrix.ConstructWithCopy(_m); + GeneralMatrix b = new GeneralMatrix(len, 1); for (int i = 0; i < len; i++) { - decimal[][] testMa = new decimal[len][]; - for (int j = 0; j < len; j++) - { - testMa[j] = new decimal[len]; - for (int k = 0; k < len; k++) - { - testMa[j][k] = _m[j][k]; - } - } - for (int j = 0; j < len; j++) - { - testMa[j][i] = _v[j]; - } - decimal di = MatrixDeterminant(testMa); - res[i] = (decimal)Math.Round(di / d0, 5); + b.Array[i][0] = _v[i]; } + GeneralMatrix x = A.Solve(b); + decimal[] res = new decimal[len]; + for (int i = 0; i < len; i++) + { + res[i] = x.Array[i][0]; + } return res; } public static decimal[][] ConvertLinearEquationsToMatrix(List equations, List variables) { - if (equations.Count == variables.Count) + if (equations == null || variables == null || equations.Count != variables.Count) return null; + + int n = equations.Count; + decimal[][] res = new decimal[n][]; + for (int i = 0; i < n; i++) { - decimal[][] res = new decimal[equations.Count][]; - for (int i = 0; i < res.Length; i++) + res[i] = new decimal[n]; + string eq = equations[i]; + if (eq.Contains("=")) { - res[i] = new decimal[equations.Count]; + string[] parts = eq.Split('='); + eq = parts[0] + "-(" + parts[1] + ")"; } - for (int i = 0; i < equations.Count; i++) + + // Use numerical evaluation to extract exact linear coefficients reliably: + // f(0, 0, ...) = c + // f(0, ..., x_k=1, ..., 0) - c = coeff_k + Dictionary zeroPts = new Dictionary(); + foreach (string v in variables) zeroPts[v] = 0m; + + decimal f0 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); + + for (int k = 0; k < n; k++) { - for (int j = 0; j < equations[i].Length; j++) - { - for (int k = 0; k < variables.Count; k++) - { - if (equations[i][j] == variables[k][0]) - { - string coeff = ""; - for (int l = j - 1; l >= 0; l--) - { - if (equations[i][l] != '*' && equations[i][l] != '+' && equations[i][l] != '-') - { - coeff += equations[i][l]; - } - if (equations[i][l] == '-') - { - coeff += '-'; - break; - } - if (equations[i][l] == '+') - { - break; - } - } - char[] charArray = coeff.ToCharArray(); - Array.Reverse(charArray); - string currentCoeff = new string(charArray); // Renamed 'coeff' to 'currentCoeff' - // Console.WriteLine("Parsing Coeff for " + variables[k] + ": '" + currentCoeff + "'"); - try { - res[i][k] = decimal.Parse(currentCoeff, CultureInfo.InvariantCulture); - } catch (Exception ex) { - Console.WriteLine($"ERROR parsing coeff '{currentCoeff}': {ex.Message}"); - throw; - } - } - } - } + string varName = variables[k]; + zeroPts[varName] = 1m; + decimal f1 = NumericalMethods.MethodMultiVar_EvaluateFunction(eq, zeroPts); + res[i][k] = f1 - f0; + zeroPts[varName] = 0m; } - return res; } - else return null; + return res; } public static decimal[][] MatrixMultiplication(decimal[][] _m1, decimal[][] _m2) { + if (_m1 == null || _m2 == null || _m1.Length == 0 || _m2.Length == 0) return null; if (_m1[0].Length == _m2.Length) { decimal[][] res = new decimal[_m1.Length][]; @@ -225,18 +145,20 @@ public class Matrix } else { - Console.WriteLine("Matrices cannot be multiplied!"); - return null; + throw new ArgumentException("Birinci matrisin sütun sayısı ile ikinci matrisin satır sayısı eşit olmalıdır."); } } + public static decimal[][] MatrixMultiplication(decimal[][] _m, decimal _c) { - decimal[][] res = _m; + if (_m == null) return null; + decimal[][] res = new decimal[_m.Length][]; for (int i = 0; i < _m.Length; i++) { - for (int j = 0; j < _m[0].Length; j++) + res[i] = new decimal[_m[i].Length]; + for (int j = 0; j < _m[i].Length; j++) { - res[i][j] *= _c; + res[i][j] = _m[i][j] * _c; } } return res; @@ -244,47 +166,42 @@ public class Matrix public static decimal[] TurnListToVector(List _vec) { - decimal[] res = new decimal[_vec.Count]; - for (int i = 0; i < _vec.Count; i++) - { - res[i] = _vec[i]; - } - return res; + return _vec.ToArray(); } + public static decimal[][] TurnListToMatrix(List> _m) { decimal[][] res = new decimal[_m.Count][]; for (int i = 0; i < _m.Count; i++) { - res[i] = new decimal[_m[i].Count]; - for (int j = 0; j < _m[i].Count; j++) - { - res[i][j] = _m[i][j]; - } + res[i] = _m[i].ToArray(); } return res; } - public static string DebugMatrix(decimal[][] _m, string _sep = " ") + public static string DebugMatrix(decimal[][] _m, string _sep = "\t") { - string sum = ""; + if (_m == null || _m.Length == 0) return ""; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < _m.Length; i++) { - for (int j = 0; j < _m[0].Length; j++) + for (int j = 0; j < _m[i].Length; j++) { - sum += _m[i][j] + ((j == _m[0].Length - 1) ? "\n" : _sep); + sb.Append(_m[i][j].ToString("0.######", CultureInfo.InvariantCulture)); + sb.Append(j == _m[i].Length - 1 ? Environment.NewLine : _sep); } } - return sum; - } - public static string DebugVector(decimal[] _v, string _sep = " ") - { - string sum = ""; - for (int i = 0; i < _v.Length; i++) - { - sum += _v[i] + "\n"; - } - return sum; + return sb.ToString(); } + public static string DebugVector(decimal[] _v, string _sep = " ") + { + if (_v == null) return ""; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + for (int i = 0; i < _v.Length; i++) + { + sb.AppendLine(_v[i].ToString("0.######", CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } } diff --git a/MathApp/MathApp/MathApp.Tests/NumericalMethods.cs b/MathApp/MathApp/MathApp.Tests/NumericalMethods.cs index 5b64409..ec2bacd 100644 --- a/MathApp/MathApp/MathApp.Tests/NumericalMethods.cs +++ b/MathApp/MathApp/MathApp.Tests/NumericalMethods.cs @@ -1,240 +1,440 @@ using DotNetMatrix; +using System; using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.Text.RegularExpressions; -using System.Text; using System.Linq; -using System; +using System.Text; +using System.Text.RegularExpressions; public class NumericalMethods { - // --- Original Methods Ported --- + public static string NormalizeEquation(string eq) + { + if (string.IsNullOrWhiteSpace(eq)) return ""; + eq = eq.Trim(); + if (eq.Contains("=")) + { + string[] parts = eq.Split('='); + if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[1])) + { + return "(" + parts[0] + ")-(" + parts[1] + ")"; + } + } + return eq; + } + + public static Function CompileFunction(string eq) + { + string norm = NormalizeEquation(eq); + Function f = new Function(); + f.Parse(norm); + if (f.Error) + { + throw new ArgumentException("Denklem ayrıştırma hatası: " + f.ErrorDescription); + } + f.Infix2Postfix(); + return f; + } + + public static decimal EvaluateCompiled(Function f, string variable, decimal point) + { + f.SetVariable(variable, point); + f.EvaluatePostfix(); + if (f.Error) + { + throw new ArithmeticException(f.ErrorDescription); + } + return f.Result; + } + + public static decimal EvaluateCompiledMultiVar(Function f, Dictionary points) + { + f.SetVariables(points); + f.EvaluatePostfix(); + if (f.Error) + { + throw new ArithmeticException(f.ErrorDescription); + } + return f.Result; + } public static decimal Method_EvaluateFunction(string eq, string variable, decimal point) { - string newEq = eq; - newEq = newEq.Replace(variable, point.ToString(CultureInfo.InvariantCulture)); - Function f = new Function(); - f.Parse(newEq); - f.Infix2Postfix(); - f.EvaluatePostfix(); - return f.m_result; + Function f = CompileFunction(eq); + return EvaluateCompiled(f, variable, point); } public static decimal MethodMultiVar_EvaluateFunction(string eq, Dictionary points) { - string newEq = eq; - foreach (KeyValuePair pt in points) - { - newEq = newEq.Replace(pt.Key, pt.Value.ToString(CultureInfo.InvariantCulture)); - } - Function f = new Function(); - f.Parse(newEq); - f.Infix2Postfix(); - f.EvaluatePostfix(); - return f.m_result; + Function f = CompileFunction(eq); + return EvaluateCompiledMultiVar(f, points); } - public static Dictionary MethodMultiVar_SolveEquationSystem(List eqs, Dictionary initPoints, int iterationCount = 5, decimal h = 0.001m) + /// + /// Solves a nonlinear or linear system of equations using Multivariable Newton-Raphson with analytical/numerical Jacobian + /// and returns step-by-step convergence logs as well as the final solution dictionary. + /// + public static Dictionary MethodMultiVar_SolveEquationSystem( + List eqs, + Dictionary initPoints, + int iterationCount = 50, + decimal h = 0.0001m) { - Dictionary dynamicPoints = new Dictionary(initPoints); - for (int itC = 0; itC < iterationCount; itC++) - { - Console.WriteLine("Iteration: " + itC); - List linearizedEqs = new List(); - List variablesStr = new List(); - List leftVector = new List(); - - for (int i = 0; i < eqs.Count; i++) - { - string le = MethodMultiVar_TaylorSeries(eqs[i], 1, dynamicPoints, h); - // Console.WriteLine("LE: " + le); - - decimal leftV = 0; - Match m = Regex.Match(le, @"^([-+]?[0-9]*\.?[0-9]+)"); - if (m.Success) - { - // Check if followed by * - if (m.Index + m.Length < le.Length && le[m.Index + m.Length] == '*') - { - leftV = 0; - // Do not strip anything, it's a coefficient - } - else - { - Console.WriteLine("Matched Constant: '" + m.Value + "'"); - try { - leftV = decimal.Parse(m.Value, CultureInfo.InvariantCulture) * -1; - } catch (OverflowException) { - Console.WriteLine("OVERFLOW parsing constant! Value too large/small."); - leftV = 0; // Fallback - } - le = le.Substring(m.Length); - } - } - - string sum = ""; - foreach (KeyValuePair p in dynamicPoints) - { - sum += p.Key + ": " + p.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) + ", "; - } - - - foreach (KeyValuePair p in dynamicPoints) - { - le = le.Replace("(" + p.Key + (p.Value < 0 ? "+" + DecimalMath.Abs(p.Value).ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : "-" + p.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture)) + ")", p.Key); - le = le.Replace("(" + p.Key + ")", p.Key); - } - - linearizedEqs.Add(le); - leftVector.Add(leftV); - } - - foreach (KeyValuePair p in dynamicPoints) - { - variablesStr.Add(p.Key); - } - Console.WriteLine("Calling ConvertLinearEquationsToMatrix"); - decimal[][] jacobianMatrix = Matrix.ConvertLinearEquationsToMatrix(linearizedEqs, variablesStr); - decimal[] leftHandVector = leftVector.ToArray(); - - // Matrix.cs in core likely has SolveEquation if I ported it. - // Let's assume Matrix.cs has it or we use GeneralMatrix directly. - // The original used Matrix.SolveEquation. - // My ported Matrix.cs from step 20 (viewed 1-663) has SolveEquation. - - Console.WriteLine("Calling Matrix.SolveEquation"); - decimal[] newPoints = Matrix.SolveEquation(jacobianMatrix, leftHandVector); - - List newPointsList = new List(); - for (int i = 0; i < newPoints.Length; i++) - { - newPointsList.Add(newPoints[i]); - } - - Dictionary tempDynamicPoints = new Dictionary(); - foreach (KeyValuePair p in dynamicPoints) - { - tempDynamicPoints.Add(p.Key, p.Value); - } - - foreach (KeyValuePair p in dynamicPoints) - { - tempDynamicPoints[p.Key] = newPointsList[0] + p.Value; - newPointsList.RemoveAt(0); - } - dynamicPoints = tempDynamicPoints; - } - - return dynamicPoints; + var logs = new List(); + return SolveEquationSystemWithLogs(eqs, initPoints, iterationCount, out logs, h); } - public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.001m) + public static Dictionary SolveEquationSystemWithLogs( + List eqs, + Dictionary initPoints, + int iterationCount, + out List logs, + decimal h = 0.0001m) { + logs = new List(); + if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) + { + throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); + } + + int n = eqs.Count; + List vars = initPoints.Keys.ToList(); + Dictionary currentPoints = new Dictionary(initPoints); + + List compiledEqs = new List(n); + for (int i = 0; i < n; i++) + { + compiledEqs.Add(CompileFunction(eqs[i])); + } + + decimal tolerance = 0.0000000001m; // 1e-10m + + for (int iter = 1; iter <= iterationCount; iter++) + { + decimal[] F = new decimal[n]; + decimal maxAbsF = 0m; + + for (int i = 0; i < n; i++) + { + F[i] = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + decimal absF = DecimalMath.Abs(F[i]); + if (absF > maxAbsF) maxAbsF = absF; + } + + if (maxAbsF <= tolerance) + { + logs.Add($"[Adım {iter - 1}] Yakınsama sağlandı! Maksimum hata |F| = {maxAbsF:E4}"); + break; + } + + // Compute Jacobian Matrix J[i][j] = df_i / dx_j via central finite difference + decimal[][] J = new decimal[n][]; + for (int i = 0; i < n; i++) + { + J[i] = new decimal[n]; + for (int j = 0; j < n; j++) + { + string vName = vars[j]; + decimal origVal = currentPoints[vName]; + + currentPoints[vName] = origVal + h; + decimal fPlus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + + currentPoints[vName] = origVal - h; + decimal fMinus = EvaluateCompiledMultiVar(compiledEqs[i], currentPoints); + + currentPoints[vName] = origVal; + J[i][j] = (fPlus - fMinus) / (2m * h); + } + } + + decimal[] negF = new decimal[n]; + for (int i = 0; i < n; i++) negF[i] = -F[i]; + + decimal[] delta; + try + { + delta = Matrix.SolveEquation(J, negF); + } + catch + { + // Perturb slightly if Jacobian is singular at initial guess (e.g. (0,0) for x^2+y^2) + for (int j = 0; j < n; j++) + { + currentPoints[vars[j]] += 0.01m * (j + 1); + } + logs.Add($"[Adım {iter}] Jakobiyen matrisi tekil (singular) noktaya denk geldi, nokta hafifçe kaydırılıyor..."); + continue; + } + + decimal maxStep = 0m; + for (int j = 0; j < n; j++) + { + currentPoints[vars[j]] += delta[j]; + decimal absD = DecimalMath.Abs(delta[j]); + if (absD > maxStep) maxStep = absD; + } + + string ptSummary = string.Join(", ", vars.Select(v => $"{v} = {currentPoints[v].ToString("0.########", CultureInfo.InvariantCulture)}")); + logs.Add($"[Adım {iter}] {ptSummary} (|Δ| = {maxStep:E3})"); + + if (maxStep <= tolerance) + { + logs.Add($"[Adım {iter}] Çözüm başarıyla yakınsadı."); + break; + } + } + + return currentPoints; + } + + public static string Method_TaylorSeries(string eq, int degree, string variable, decimal point, decimal h = 0.005m) + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; decimal constant = Method_EvaluateFunction(eq, variable, point); - constant = DecimalMath.Abs(constant) <= 0.001m ? 0 : constant; - string newEq = constant != 0 ? constant.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : ""; - for (int i = 1; i < degree + 1; i++) + if (DecimalMath.Abs(constant) <= 0.000001m) constant = 0; + + List terms = new List(); + if (constant != 0) { - decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, h); + terms.Add(FormatCoeff(constant)); + } + + for (int i = 1; i <= degree; i++) + { + decimal step = i >= 4 ? 0.01m : h; + decimal der = Method_NumericalDifferentiation(eq, i, variable, point, 4, step); decimal fact = Factorial(i); - decimal coeff = (der / fact); - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; + decimal coeff = der / fact; - string addingSTR = ""; - if (point < 0) - { - addingSTR = "+" + DecimalMath.Abs(point).ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); - } - else if (point > 0) - { - addingSTR = "-" + point.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); - } + if (DecimalMath.Abs(coeff) <= 0.000001m) continue; - varSTR += coeff.ToString(CultureInfo.InvariantCulture) + "*(" + variable + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) + ""); - newEq += varSTR; + string varPart = FormatVarPower(variable, point, i); + string coeffStr = FormatTermWithCoeff(coeff, varPart, terms.Count == 0); + terms.Add(coeffStr); } - if (constant == 0 && newEq.Length > 0 && newEq[0] == '+') newEq = newEq.Substring(1); - return newEq; + + if (terms.Count == 0) return "0"; + return string.Join(" ", terms); } - public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.001m) + public static string MethodMultiVar_TaylorSeries(string eq, int degree, Dictionary points, decimal h = 0.005m) { - decimal constant = MethodMultiVar_EvaluateFunction(eq, points); - constant = DecimalMath.Abs(constant) <= 0.0001m ? 0 : constant; - string newEq = constant != 0 ? constant.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture) : ""; - for (int i = 1; i < degree + 1; i++) + if (points == null || points.Count == 0) return "0"; + + Function compiled = CompileFunction(eq); + decimal constant = EvaluateCompiledMultiVar(compiled, points); + if (DecimalMath.Abs(constant) <= 0.00001m) constant = 0; + + List terms = new List(); + if (constant != 0) { - foreach (KeyValuePair pt in points) - { - decimal partDer = Method_NumericalPartialDifferentiation(eq, i, pt.Key, points, 4, h); - decimal fact = Factorial(i); - decimal coeff = partDer / fact; - string varSTR = ""; - if (coeff > 0) varSTR = "+"; - if (coeff == 0) continue; + terms.Add(FormatCoeff(constant)); + } - string addingSTR = ""; - if (pt.Value < 0) + List varNames = points.Keys.ToList(); + int kVars = varNames.Count; + + for (int totalDeg = 1; totalDeg <= degree; totalDeg++) + { + List multiIndices = GenerateMultiIndices(kVars, totalDeg); + foreach (int[] alpha in multiIndices) + { + decimal mixedDer = ComputeMixedPartialDerivative(compiled, varNames, alpha, points, h); + decimal denom = 1m; + for (int j = 0; j < kVars; j++) { - addingSTR = "+" + DecimalMath.Abs(pt.Value).ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); + denom *= Factorial(alpha[j]); } - else if (pt.Value > 0) + + decimal coeff = mixedDer / denom; + if (DecimalMath.Abs(coeff) <= 0.00001m) continue; + + List factors = new List(); + for (int j = 0; j < kVars; j++) { - addingSTR = "-" + pt.Value.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture); + if (alpha[j] > 0) + { + string vName = varNames[j]; + factors.Add(FormatVarPower(vName, points[vName], alpha[j])); + } } - varSTR += coeff.ToString(CultureInfo.InvariantCulture) + "*(" + pt.Key + addingSTR + (i == 1 ? ")" : ")^" + i.ToString("0." + new string('#', 339), CultureInfo.InvariantCulture)); - newEq += varSTR; + + string varPart = string.Join(" * ", factors); + terms.Add(FormatTermWithCoeff(coeff, varPart, terms.Count == 0)); } } - if (constant == 0 && newEq.Length > 0 && newEq[0] == '+') newEq = newEq.Substring(1); - // Assuming intent was to do nothing or it's buggy. I'll leave it as is (or fix it). - return newEq; + + if (terms.Count == 0) return "0"; + return string.Join(" ", terms); } - public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.001m) + private static List GenerateMultiIndices(int numVars, int totalSum) { - // Lipschitz check suppressed/incomplete in original - decimal init = initialValue; + List results = new List(); + int[] current = new int[numVars]; + GenerateMultiIndicesRecursive(numVars, totalSum, 0, current, results); + return results; + } + + private static void GenerateMultiIndicesRecursive(int numVars, int remaining, int idx, int[] current, List results) + { + if (idx == numVars - 1) + { + current[idx] = remaining; + results.Add((int[])current.Clone()); + return; + } + for (int v = remaining; v >= 0; v--) + { + current[idx] = v; + GenerateMultiIndicesRecursive(numVars, remaining - v, idx + 1, current, results); + } + } + + private static decimal ComputeMixedPartialDerivative( + Function f, + List varNames, + int[] orders, + Dictionary basePoints, + decimal h) + { + Dictionary workPoints = new Dictionary(basePoints); + return ComputeMixedRecursive(f, varNames, orders, 0, workPoints, h); + } + + private static decimal ComputeMixedRecursive( + Function f, + List varNames, + int[] orders, + int varIndex, + Dictionary workPoints, + decimal h) + { + while (varIndex < orders.Length && orders[varIndex] == 0) + { + varIndex++; + } + + if (varIndex >= orders.Length) + { + return EvaluateCompiledMultiVar(f, workPoints); + } + + string vName = varNames[varIndex]; + int m = orders[varIndex]; + decimal origVal = workPoints[vName]; + + // Central finite difference weights for order m + decimal sum = 0m; + for (int i = 0; i <= m; i++) + { + decimal shift = (m - 2m * i) * (h * 0.5m); + workPoints[vName] = origVal + shift; + decimal sign = (i % 2 == 0) ? 1m : -1m; + decimal comb = Combination(m, i); + decimal subVal = ComputeMixedRecursive(f, varNames, orders, varIndex + 1, workPoints, h); + sum += sign * comb * subVal; + } + + workPoints[vName] = origVal; + return sum / DecimalMath.Pow(h, m); + } + + private static string FormatCoeff(decimal c) + { + decimal rounded = Math.Round(c, 6); + foreach (int denom in new[] { 1, 2, 3, 4, 6, 8, 12 }) + { + decimal candidate = Math.Round(c * denom) / (decimal)denom; + if (DecimalMath.Abs(c - candidate) < 0.00005m) + { + rounded = candidate; + break; + } + } + return rounded.ToString("0.######", CultureInfo.InvariantCulture); + } + + private static string FormatVarPower(string variable, decimal center, int power) + { + string core; + if (center == 0m) + { + core = variable; + } + else if (center > 0m) + { + core = $"({variable} - {FormatCoeff(center)})"; + } + else + { + core = $"({variable} + {FormatCoeff(DecimalMath.Abs(center))})"; + } + + if (power == 1) return core; + return $"{core}^{power}"; + } + + private static string FormatTermWithCoeff(decimal coeff, string varPart, bool isFirst) + { + decimal absC = DecimalMath.Abs(coeff); + string sign = coeff < 0 ? (isFirst ? "-" : "- ") : (isFirst ? "" : "+ "); + string cStr = FormatCoeff(absC); + + if (cStr == "1") + { + return $"{sign}{varPart}"; + } + return $"{sign}{cStr}*{varPart}"; + } + + public static decimal Method_NewtonRaphson(string eq, string variable, decimal initialValue, int iterationCount, decimal h = 0.0001m) + { + Function f = CompileFunction(eq); + decimal curr = initialValue; for (int i = 0; i < iterationCount; i++) { - decimal next = init - Method_EvaluateFunction(eq, variable, init) / Method_NumericalDifferentiation(eq, 1, variable, init, 6, h); - init = next; - } - return init; - } + decimal fx = EvaluateCompiled(f, variable, curr); + if (DecimalMath.Abs(fx) <= 1e-12m) break; - // Overload for single-variable Newton-Raphson from UIController's simpler usage (assuming UIController calls this one if I didn't verify signature) - // UIController calls: NumericalMethods.Method_NewtonRaphson(eq, variable, initialP, iterCount); - // Matches the one above. - - // My previous implementation had a simplified one. I should keep the one matching signature. + decimal dfx = (EvaluateCompiled(f, variable, curr + h) - EvaluateCompiled(f, variable, curr - h)) / (2m * h); + if (DecimalMath.Abs(dfx) <= 1e-15m) break; + + curr = curr - fx / dfx; + } + return curr; + } public static decimal Method_BisectionMethod(string eq, string variable, decimal lowerValue, decimal higherValue, int iterationCount) { - if (lowerValue >= higherValue) - return 0; + if (lowerValue >= higherValue) return lowerValue; - decimal mp = (lowerValue + higherValue) / 2; + Function f = CompileFunction(eq); + decimal fa = EvaluateCompiled(f, variable, lowerValue); + if (DecimalMath.Abs(fa) <= 1e-12m) return lowerValue; + decimal fb = EvaluateCompiled(f, variable, higherValue); + if (DecimalMath.Abs(fb) <= 1e-12m) return higherValue; + + decimal mp = (lowerValue + higherValue) / 2m; for (int i = 0; i < iterationCount; i++) { - mp = (lowerValue + higherValue) / 2; + mp = (lowerValue + higherValue) / 2m; + decimal evMiddle = EvaluateCompiled(f, variable, mp); - decimal evLower = Method_EvaluateFunction(eq, variable, lowerValue); - // decimal evHigher = Method_EvaluateFunction(eq, variable, higherValue); // unused - decimal evMiddle = Method_EvaluateFunction(eq, variable, mp); + if (DecimalMath.Abs(evMiddle) <= 1e-12m) break; - if (evLower * evMiddle < 0) + if (fa * evMiddle <= 0) { higherValue = mp; + fb = evMiddle; } else { lowerValue = mp; + fa = evMiddle; } } @@ -243,34 +443,27 @@ public class NumericalMethods public static decimal Method_Derivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - decimal sum = 0; - for (int i = 0; i <= degree; i++) - { - sum += DecimalMath.Pow(-1, i) * Combination(degree, i) * Method_EvaluateFunction(eq, variable, point + (degree - i) * h); - } - return sum / DecimalMath.Pow(h, degree); + return Method_NumericalDifferentiation(eq, degree, variable, point, 4, h); } public static decimal Method_PartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) { - decimal sum = 0; - Dictionary testPS = new Dictionary(points); - decimal firstToVar = testPS[toVar]; - for (int i = 0; i <= degree; i++) - { - testPS[toVar] = firstToVar + (degree - i) * h; - sum += DecimalMath.Pow(-1, i) * Combination(degree, i) * MethodMultiVar_EvaluateFunction(eq, testPS); - } - return sum / DecimalMath.Pow(h, degree); + return Method_NumericalPartialDifferentiation(eq, degree, toVar, points, 4, h); } public static decimal Method_NumericalDifferentiation(string eq, int degree, string variable, decimal point, int accuracy = 2, decimal h = 0.001m) { int m = degree, n = accuracy; + if (m >= 11) { n = 2; h = 0.08m; } + else if (m == 10) { n = 2; h = 0.04m; } + else if (m == 9) { n = 4; h = 0.015m; } + else if (m >= 7 && h < 0.012m) h = 0.012m; + + Function f = CompileFunction(eq); int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; decimal[][] _matrix = new decimal[2 * p + 1][]; - decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], + decimal[] _rhsVector = new decimal[2 * p + 1], functionPointsX = new decimal[2 * p + 1], functionPointsY = new decimal[2 * p + 1]; for (int i = 0; i < _matrix.Length; i++) @@ -278,20 +471,12 @@ public class NumericalMethods _matrix[i] = new decimal[2 * p + 1]; for (int j = 0; j < _matrix[i].Length; j++) { - _matrix[i][j] = (decimal)Math.Pow(-p + j, i); - } - - if (i != m) - { - _rhsVector[i] = 0; - } - else if (i == m) - { - _rhsVector[i] = Factorial(m); + _matrix[i][j] = DecimalMath.PowerN(-p + j, i); } + _rhsVector[i] = (i == m) ? Factorial(m) : 0m; functionPointsX[i] = point - (p - i) * h; - functionPointsY[i] = Method_EvaluateFunction(eq, variable, functionPointsX[i]); + functionPointsY[i] = EvaluateCompiled(f, variable, functionPointsX[i]); } GeneralMatrix _A = new GeneralMatrix(_matrix); @@ -315,6 +500,7 @@ public class NumericalMethods public static decimal Method_NumericalPartialDifferentiation(string eq, int degree, string toVar, Dictionary points, int accuracy = 2, decimal h = 0.001m) { + Function f = CompileFunction(eq); int m = degree, n = accuracy; int p = (2 * (int)Math.Floor((m + 1) / 2.0) - 2 + n) / 2; @@ -327,11 +513,10 @@ public class NumericalMethods _matrix[i] = new decimal[2 * p + 1]; for (int j = 0; j < _matrix[i].Length; j++) { - _matrix[i][j] = (decimal)Math.Pow(-p + j, i); + _matrix[i][j] = DecimalMath.PowerN(-p + j, i); } - if (i != m) _rhsVector[i] = 0; - else if (i == m) _rhsVector[i] = Factorial(m); + _rhsVector[i] = (i == m) ? Factorial(m) : 0m; } foreach (KeyValuePair item in points) @@ -355,7 +540,7 @@ public class NumericalMethods { pair.Add(item.Key, item.Value[i]); } - functionPointsRange[i] = MethodMultiVar_EvaluateFunction(eq, pair); + functionPointsRange[i] = EvaluateCompiledMultiVar(f, pair); } GeneralMatrix _A = new GeneralMatrix(_matrix); @@ -376,18 +561,35 @@ public class NumericalMethods public static decimal Factorial(int num) { - if (num >= 2) return num * Factorial(num - 1); - else return 1; + if (num < 0) return 0m; + decimal res = 1m; + for (int i = 2; i <= num; i++) res *= i; + return res; } public static decimal Combination(int n, int k) { - return Factorial(n) / (Factorial(n - k) * Factorial(k)); + if (k < 0 || k > n || n < 0) return 0m; + if (k == 0 || k == n) return 1m; + if (k > n - k) k = n - k; + decimal res = 1m; + for (int i = 1; i <= k; i++) + { + res = (res * (n - k + i)) / i; + } + return res; } - + public static decimal Permutation(int n, int k) { - return Factorial(n) / Factorial(n - k); + if (k < 0 || k > n || n < 0) return 0m; + if (k == 0) return 1m; + decimal res = 1m; + for (int i = 0; i < k; i++) + { + res *= (n - i); + } + return res; } public static string GenerateCombinations(string chars, string prefix, int length) @@ -396,6 +598,7 @@ public class NumericalMethods GenerateCombinationsRecursive(prefix, chars, length, sb); return sb.ToString(); } + static void GenerateCombinationsRecursive(string prefix, string chars, int length, StringBuilder sb) { if (length == 0) @@ -410,142 +613,502 @@ public class NumericalMethods } } - // --- Added Linear Solvers (Optional but kept for completeness if UI uses them) --- - // Update: UI uses MethodMultiVar_SolveEquationSystem for System Solver now (based on UIController) - // But I implemented btnSolveSystem_Click in MainForm.cs to use Method_LUDecomposition previously. - // I should update MainForm.cs to use MethodMultiVar_SolveEquationSystem if it's non-linear or general. - // The original app used MethodMultiVar_SolveEquationSystem (Newton-Raphson) for general systems. - - // So I should keep MethodMultiVar_SolveEquationSystem and update MainForm to use IT instead of LUDecomposition if I want to match original behavior. - - // I'll keep the linear solvers just in case. - - public static List Method_Inverse(List _eq, List _vars) + /// + /// Gauss-Seidel Iterative Linear System Solver with Diagonal Dominance Verification & Row Reordering. + /// Ported and enhanced from NumericalMethods / NumericalMethods2. + /// + public static Dictionary Method_GaussSeidel( + List eqs, + Dictionary initPoints, + int iterationCount, + out List logs) { - // Implementation from previous turn - decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(_eq, _vars); - if (A == null) return null; - decimal[] B = new decimal[_eq.Count]; - for (int i = 0; i < _eq.Count; i++) + logs = new List(); + if (eqs == null || initPoints == null || eqs.Count == 0 || eqs.Count != initPoints.Count) { - int ind = _eq[i].IndexOf('='); - if (ind != -1) B[i] = decimal.Parse(_eq[i].Substring(ind + 1), CultureInfo.InvariantCulture); - else B[i] = 0; + throw new ArgumentException("Denklem sayısı ile değişken sayısı birbirine eşit olmalıdır."); } - + + int n = eqs.Count; + List vars = initPoints.Keys.ToList(); + + // Extract linear matrix A and right-hand vector b such that A * x = b + // Note: ConvertLinearEquationsToMatrix evaluates f(x) = LHS - RHS = A*x - b + decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); + decimal[] b = new decimal[n]; + Dictionary zeroPts = new Dictionary(); + foreach (string v in vars) zeroPts[v] = 0m; + + for (int i = 0; i < n; i++) + { + string normEq = NormalizeEquation(eqs[i]); + // f(0) = -b => b = -f(0) + b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); + } + + // Check / reorder rows for diagonal dominance: |a_ii| > sum_{j != i} |a_ij| + int[] dominantColForRow = new int[n]; + bool strictDominance = true; + for (int i = 0; i < n; i++) + { + int domCol = -1; + for (int j = 0; j < n; j++) + { + decimal sumOthers = 0m; + for (int k = 0; k < n; k++) + { + if (k != j) sumOthers += DecimalMath.Abs(A[i][k]); + } + if (DecimalMath.Abs(A[i][j]) >= sumOthers && DecimalMath.Abs(A[i][j]) > 0m) + { + domCol = j; + break; + } + } + dominantColForRow[i] = domCol; + if (domCol == -1) strictDominance = false; + } + + // Attempt to permute rows if each row has a distinct dominant column + if (strictDominance && dominantColForRow.Distinct().Count() == n) + { + decimal[][] newA = new decimal[n][]; + decimal[] newB = new decimal[n]; + for (int i = 0; i < n; i++) + { + int targetRow = dominantColForRow[i]; + newA[targetRow] = A[i]; + newB[targetRow] = b[i]; + } + A = newA; + b = newB; + logs.Add("✓ Köşegen baskınlığı (Diagonal Dominance) doğrulandı (|a_ii| ≥ Σ|a_ij|)."); + } + else + { + logs.Add("⚠️ Uyarı: Matris tam köşegen baskın değil; Gauss-Seidel yakınsamayabilir."); + } + + decimal[] x = new decimal[n]; + for (int i = 0; i < n; i++) x[i] = initPoints[vars[i]]; + + decimal tol = 1e-10m; + for (int iter = 1; iter <= iterationCount; iter++) + { + decimal maxDiff = 0m; + for (int i = 0; i < n; i++) + { + if (DecimalMath.Abs(A[i][i]) <= 1e-15m) + { + throw new ArithmeticException($"Köşegen elemanı A[{i + 1},{i + 1}] = 0 olduğu için Gauss-Seidel uygulanamaz."); + } + + decimal sigma = 0m; + for (int j = 0; j < n; j++) + { + if (j != i) sigma += A[i][j] * x[j]; + } + + decimal nextXi = (b[i] - sigma) / A[i][i]; + decimal diff = DecimalMath.Abs(nextXi - x[i]); + if (diff > maxDiff) maxDiff = diff; + x[i] = nextXi; + } + + string stepStr = string.Join(", ", Enumerable.Range(0, n).Select(idx => $"{vars[idx]} = {x[idx].ToString("0.########", CultureInfo.InvariantCulture)}")); + logs.Add($"[Adım {iter,2}] {stepStr} (|Δ| = {maxDiff:E3})"); + + if (maxDiff <= tol) + { + logs.Add($"✓ Gauss-Seidel {iter}. adımda başarıyla yakınsadı."); + break; + } + } + + Dictionary result = new Dictionary(); + for (int i = 0; i < n; i++) result[vars[i]] = x[i]; + return result; + } + + public static Dictionary Method_LinearMatrixSolve( + List eqs, + List vars, + string methodType, + out List logs) + { + logs = new List(); + int n = eqs.Count; + decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(eqs, vars); + decimal[] b = new decimal[n]; + + Dictionary zeroPts = new Dictionary(); + foreach (string v in vars) zeroPts[v] = 0m; + bool isNonLinear = false; + for (int i = 0; i < n; i++) + { + string normEq = NormalizeEquation(eqs[i]); + b[i] = -MethodMultiVar_EvaluateFunction(normEq, zeroPts); + + if (vars.Count > 0) + { + zeroPts[vars[0]] = 2m; + decimal f2 = MethodMultiVar_EvaluateFunction(normEq, zeroPts); + zeroPts[vars[0]] = 0m; + if (DecimalMath.Abs(f2 - (2m * A[i][0] - b[i])) > 1e-4m) + { + isNonLinear = true; + } + } + } + + if (isNonLinear) + { + logs.Add("UYARI: Denklemler doğrusal değil. Çözüm doğrusal yaklaşım olarak sunulmuştur."); + } + + logs.Add("--- Katsayılar Matrisi (A) ve Sağ Taraf Vektörü (b) ---"); + for (int i = 0; i < n; i++) + { + string rowStr = string.Join(" ", A[i].Select(v => $"{v,8:0.####}")); + logs.Add($" [ {rowStr} ] | [ {b[i],8:0.####} ]"); + } + logs.Add(""); + GeneralMatrix gA = new GeneralMatrix(A); - GeneralMatrix gB = new GeneralMatrix(B, B.Length); - GeneralMatrix gX = gA.Solve(gB); - decimal[] X = gX.ColumnPackedCopy; - - List res = new List(); - for (int i = 0; i < X.Length; i++) res.Add(_vars[i] + " = " + X[i].ToString("F5", CultureInfo.InvariantCulture)); + GeneralMatrix gB = new GeneralMatrix(n, 1); + for (int i = 0; i < n; i++) gB.Array[i][0] = b[i]; + + GeneralMatrix gX; + if (methodType == "INVERSE") + { + logs.Add("Yöntem: Ters Matris (X = A⁻¹ · b)"); + GeneralMatrix invA = gA.Inverse(); + gX = invA.Multiply(gB); + } + else if (methodType == "QR") + { + logs.Add("Yöntem: QR Ayrışımı (Q·R·X = b)"); + gX = gA.QRD().Solve(gB); + } + else + { + logs.Add("Yöntem: LU Ayrışımı (L·U·X = P·b)"); + gX = gA.LUD().Solve(gB); + } + + Dictionary res = new Dictionary(); + for (int i = 0; i < n; i++) + { + res[vars[i]] = gX.Array[i][0]; + logs.Add($" {vars[i]} = {Math.Round(gX.Array[i][0], 8).ToString("0.########", CultureInfo.InvariantCulture)}"); + } return res; } - public static List Method_LUDecomposition(List _eq, List _vars) + public static decimal Method_BackwardDifferenceDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - // Implementation from previous turn - decimal[][] A = Matrix.ConvertLinearEquationsToMatrix(_eq, _vars); - if (A == null) return null; - decimal[] B = new decimal[_eq.Count]; - for (int i = 0; i < _eq.Count; i++) - { - int ind = _eq[i].IndexOf('='); - if (ind != -1) B[i] = decimal.Parse(_eq[i].Substring(ind + 1), CultureInfo.InvariantCulture); - else B[i] = 0; - } - - GeneralMatrix gA = new GeneralMatrix(A); - GeneralMatrix gB = new GeneralMatrix(B, B.Length); - GeneralMatrix gX = gA.Solve(gB); - decimal[] X = gX.ColumnPackedCopy; - - List res = new List(); - for (int i = 0; i < X.Length; i++) res.Add(_vars[i] + " = " + X[i].ToString("F5", CultureInfo.InvariantCulture)); - return res; + Function f = CompileFunction(eq); + decimal f0 = EvaluateCompiled(f, variable, point); + decimal f1 = EvaluateCompiled(f, variable, point - h); + decimal f2 = EvaluateCompiled(f, variable, point - 2m * h); + + if (degree == 1) + { + return (3m * f0 + f2 - 4m * f1) / (2m * h); + } + else if (degree == 2) + { + return (f0 + f2 - 2m * f1) / (h * h); + } + else if (degree == 3) + { + decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); + decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); + return (3m * f4 - 14m * f3 + 24m * f2 - 18m * f1 + 5m * f0) / (2m * h * h * h); + } + else if (degree == 4) + { + decimal f3 = EvaluateCompiled(f, variable, point - 3m * h); + decimal f4 = EvaluateCompiled(f, variable, point - 4m * h); + decimal f5 = EvaluateCompiled(f, variable, point - 5m * h); + return (-2m * f5 + 11m * f4 - 24m * f3 + 26m * f2 - 14m * f1 + 3m * f0) / (h * h * h * h); + } + else + { + return Method_ForwardBinomialDerivative(eq, degree, variable, point, h); + } } - // Additional wrappers for MainForm compatibility if needed - public static List Method_NewtonRaphson(string _eq, decimal _initialPoint, int _iterationCount) + public static decimal Method_ForwardBinomialDerivative(string eq, int degree, string variable, decimal point, decimal h = 0.001m) { - // Wrapper for UI - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - decimal res = Method_NewtonRaphson(_eq, "x", _initialPoint, _iterationCount); - return new List { res.ToString(CultureInfo.InvariantCulture) }; + Function f = CompileFunction(eq); + decimal sum = 0m; + for (int i = 0; i <= degree; i++) + { + decimal sign = (i % 2 == 0) ? 1m : -1m; + sum += sign * Combination(degree, i) * EvaluateCompiled(f, variable, point + (degree - i) * h); + } + return sum / DecimalMath.Pow(h, degree); } - - public static List Method_Bisection(string _eq, decimal _min, decimal _max, int _iterationCount) - { - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - decimal res = Method_BisectionMethod(_eq, "x", _min, _max, _iterationCount); - return new List { res.ToString(CultureInfo.InvariantCulture) }; - } - - public static List Method_Secant(string _eq, decimal _min, decimal _max, int _iterationCount) - { - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - - decimal x0 = _min; - decimal x1 = _max; - decimal x2 = 0; - - for(int i=0; i<_iterationCount; i++) - { - decimal f0 = Method_EvaluateFunction(_eq, "x", x0); - decimal f1 = Method_EvaluateFunction(_eq, "x", x1); - - if (f1 - f0 == 0) break; // Avoid divide by zero - - x2 = x1 - f1 * (x1 - x0) / (f1 - f0); - x0 = x1; - x1 = x2; - - if (DecimalMath.Abs(f1) < 0.00000001m) break; - } - - return new List { x2.ToString(CultureInfo.InvariantCulture) }; - } - public static List Method_RegulaFalsi(string _eq, decimal _min, decimal _max, int _iterationCount) + public static decimal Method_ForwardBinomialPartialDerivative(string eq, int degree, string toVar, Dictionary points, decimal h = 0.001m) { - if (_eq.Contains("=")) - { - string[] parts = _eq.Split('='); - _eq = parts[0] + "-(" + parts[1] + ")"; - } - - decimal a = _min; - decimal b = _max; - decimal c = 0; - - for(int i=0; i<_iterationCount; i++) - { - decimal fa = Method_EvaluateFunction(_eq, "x", a); - decimal fb = Method_EvaluateFunction(_eq, "x", b); - - if (fa * fb >= 0) return new List { "Root not bracketed or multiple roots" }; - - c = (a * fb - b * fa) / (fb - fa); - decimal fc = Method_EvaluateFunction(_eq, "x", c); - - if (fc == 0) break; - else if (fa * fc < 0) b = c; - else a = c; - } - - return new List { c.ToString(CultureInfo.InvariantCulture) }; + Function f = CompileFunction(eq); + decimal sum = 0m; + Dictionary testPS = new Dictionary(points); + decimal firstToVar = testPS[toVar]; + for (int i = 0; i <= degree; i++) + { + testPS[toVar] = firstToVar + (degree - i) * h; + decimal sign = (i % 2 == 0) ? 1m : -1m; + sum += sign * Combination(degree, i) * EvaluateCompiledMultiVar(f, testPS); + } + return sum / DecimalMath.Pow(h, degree); + } + + // --- Root Finding Methods with Full Iteration Logs & Variable Support --- + + public static List Method_NewtonRaphson(string _eq, decimal _initialPoint, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + decimal x = _initialPoint; + decimal h = 0.0001m; + decimal tol = 1e-12m; + + logs.Add($"--- Newton-Raphson Yöntemi (Başlangıç: {variable}₀ = {x.ToString(CultureInfo.InvariantCulture)}) ---"); + + for (int i = 1; i <= _iterationCount; i++) + { + decimal fx = EvaluateCompiled(f, variable, x); + decimal dfx = (EvaluateCompiled(f, variable, x + h) - EvaluateCompiled(f, variable, x - h)) / (2m * h); + + if (DecimalMath.Abs(dfx) <= 1e-15m) + { + logs.Add($"[Adım {i}] Türev sıfıra çok yakın (f'({variable}) ≈ 0). İşlem durduruldu."); + break; + } + + decimal nextX = x - fx / dfx; + decimal err = DecimalMath.Abs(nextX - x); + x = nextX; + + logs.Add($"[Adım {i,2}] {variable} = {x.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fx.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (err <= tol || DecimalMath.Abs(fx) <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, x); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {x.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_Bisection(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal a = _min; + decimal b = _max; + if (a >= b) + { + return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; + } + + decimal fa = EvaluateCompiled(f, variable, a); + decimal fb = EvaluateCompiled(f, variable, b); + + if (DecimalMath.Abs(fa) <= 1e-12m) + { + logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + if (DecimalMath.Abs(fb) <= 1e-12m) + { + logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + + if (fa * fb > 0) + { + return new List + { + $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", + $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", + "Bisection (İkiye Bölme) yöntemi için f(Min) * f(Max) <= 0 olmalıdır." + }; + } + + logs.Add($"--- Bisection (İkiye Bölme) Yöntemi [{a}, {b}] ---"); + decimal mid = (a + b) / 2m; + decimal tol = 1e-11m; + + for (int i = 1; i <= _iterationCount; i++) + { + mid = (a + b) / 2m; + decimal fMid = EvaluateCompiled(f, variable, mid); + decimal width = (b - a) / 2m; + + logs.Add($"[Adım {i,2}] {variable} = {mid.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fMid.ToString("E3", CultureInfo.InvariantCulture),-11} | Aralık: [{a:0.####}, {b:0.####}]"); + + if (DecimalMath.Abs(fMid) <= tol || width <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + + if (fa * fMid <= 0) + { + b = mid; + fb = fMid; + } + else + { + a = mid; + fa = fMid; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, mid); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {mid.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_Secant(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal x0 = _min; + decimal x1 = _max; + decimal x2 = x1; + decimal tol = 1e-11m; + + logs.Add($"--- Secant (Kiriş) Yöntemi ({variable}₀ = {x0}, {variable}₁ = {x1}) ---"); + + for (int i = 1; i <= _iterationCount; i++) + { + decimal f0 = EvaluateCompiled(f, variable, x0); + decimal f1 = EvaluateCompiled(f, variable, x1); + + if (DecimalMath.Abs(f1 - f0) <= 1e-15m) + { + logs.Add($"[Adım {i}] f({variable}₁) - f({variable}₀) ≈ 0 oldu. İşlem durduruldu."); + break; + } + + x2 = x1 - f1 * (x1 - x0) / (f1 - f0); + decimal err = DecimalMath.Abs(x2 - x1); + x0 = x1; + x1 = x2; + + decimal f2 = EvaluateCompiled(f, variable, x2); + logs.Add($"[Adım {i,2}] {variable} = {x2.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {f2.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (err <= tol || DecimalMath.Abs(f2) <= tol) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, x2); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {x2.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; + } + + public static List Method_RegulaFalsi(string _eq, decimal _min, decimal _max, int _iterationCount, string variable = "x") + { + if (string.IsNullOrWhiteSpace(variable)) variable = "x"; + Function f = CompileFunction(_eq); + List logs = new List(); + + decimal a = _min; + decimal b = _max; + if (a >= b) + { + return new List { "Hata: Alt sınır (Min) üst sınırdan (Max) küçük olmalıdır." }; + } + + decimal fa = EvaluateCompiled(f, variable, a); + decimal fb = EvaluateCompiled(f, variable, b); + + if (DecimalMath.Abs(fa) <= 1e-12m) + { + logs.Add($"✓ Alt sınır {variable} = {a} zaten bir köktür: f({a}) = {fa}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {a.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + if (DecimalMath.Abs(fb) <= 1e-12m) + { + logs.Add($"✓ Üst sınır {variable} = {b} zaten bir köktür: f({b}) = {fb}"); + logs.Add($">>> BULUNAN KÖK: {variable} = {b.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = 0)"); + return logs; + } + + if (fa * fb > 0) + { + return new List + { + $"Uyarı: Seçilen [{a}, {b}] aralığında işaret değişimi yok!", + $"f({a}) = {fa:0.######} ve f({b}) = {fb:0.######} aynı işaretli.", + "Regula Falsi yöntemi için f(Min) * f(Max) <= 0 olmalıdır." + }; + } + + logs.Add($"--- Regula Falsi (Yer Değiştirme) Yöntemi [{a}, {b}] ---"); + decimal c = a; + decimal tol = 1e-11m; + int side = 0; + + for (int i = 1; i <= _iterationCount; i++) + { + if (DecimalMath.Abs(fb - fa) <= 1e-15m) break; + + decimal prevC = c; + c = (a * fb - b * fa) / (fb - fa); + decimal fc = EvaluateCompiled(f, variable, c); + decimal err = DecimalMath.Abs(c - prevC); + + logs.Add($"[Adım {i,2}] {variable} = {c.ToString("0.############", CultureInfo.InvariantCulture),-18} | f({variable}) = {fc.ToString("E3", CultureInfo.InvariantCulture),-11} | |Δ| = {err.ToString("E3", CultureInfo.InvariantCulture)}"); + + if (DecimalMath.Abs(fc) <= tol || (i > 1 && err <= tol)) + { + logs.Add($"✓ Yakınsama {i}. adımda tamamlandı."); + break; + } + + if (fa * fc <= 0) + { + b = c; + fb = fc; + if (side == -1) fa *= 0.5m; + side = -1; + } + else + { + a = c; + fa = fc; + if (side == 1) fb *= 0.5m; + side = 1; + } + } + + decimal finalFx = EvaluateCompiled(f, variable, c); + logs.Add(""); + logs.Add($">>> BULUNAN KÖK: {variable} = {c.ToString("0.##########", CultureInfo.InvariantCulture)} (f({variable}) = {finalFx.ToString("0.##########", CultureInfo.InvariantCulture)})"); + return logs; } } diff --git a/MathApp/MathApp/MathApp.Tests/SingularValueDecomposition.cs b/MathApp/MathApp/MathApp.Tests/SingularValueDecomposition.cs index 3a51b8e..206d5f6 100644 --- a/MathApp/MathApp/MathApp.Tests/SingularValueDecomposition.cs +++ b/MathApp/MathApp/MathApp.Tests/SingularValueDecomposition.cs @@ -12,9 +12,19 @@ namespace DotNetMatrix public SingularValueDecomposition(GeneralMatrix Arg) { - decimal[][] A = Arg.ArrayCopy; m = Arg.RowDimension; n = Arg.ColumnDimension; + + if (m < n) + { + SingularValueDecomposition svdTrans = new SingularValueDecomposition(Arg.Transpose()); + s = (decimal[])svdTrans.s.Clone(); + U = svdTrans.V; + V = svdTrans.U; + return; + } + + decimal[][] A = Arg.ArrayCopy; int nu = System.Math.Min(m, n); s = new decimal[System.Math.Min(m + 1, n)]; U = new decimal[m][]; @@ -226,8 +236,8 @@ namespace DotNetMatrix int pp = p - 1; int iter = 0; - decimal eps = (decimal)Math.Pow(2.0f, - 52.0f); - while (p > 0) + decimal eps = DecimalMath.Pow(2.0m, -64.0m); + while (p > 0 && iter < 150) { int k, kase; for (k = p - 2; k >= - 1; k--) @@ -456,11 +466,12 @@ namespace DotNetMatrix { get { - GeneralMatrix X = new GeneralMatrix(n, n); + int nu = System.Math.Min(m, n); + GeneralMatrix X = new GeneralMatrix(nu, nu); decimal[][] S = X.Array; - for (int i = 0; i < n; i++) + for (int i = 0; i < nu; i++) { - for (int j = 0; j < n; j++) + for (int j = 0; j < nu; j++) { S[i][j] = 0.0m; } @@ -472,12 +483,12 @@ namespace DotNetMatrix public virtual GeneralMatrix GetU() { - return new GeneralMatrix(U, m, System.Math.Min(m + 1, n)); + return new GeneralMatrix(U, m, System.Math.Min(m, n)); } public virtual GeneralMatrix GetV() { - return new GeneralMatrix(V, n, n); + return new GeneralMatrix(V, n, System.Math.Min(m, n)); } public virtual decimal Norm2() @@ -487,7 +498,8 @@ namespace DotNetMatrix public virtual decimal Condition() { - return s[0] / s[System.Math.Min(m, n) - 1]; + decimal minS = s[System.Math.Min(m, n) - 1]; + return minS != 0m ? s[0] / minS : decimal.MaxValue; } public virtual int Rank() diff --git a/MathApp/MathApp/MathApp.csproj b/MathApp/MathApp/MathApp.csproj index 1f1ef34..00b66aa 100644 --- a/MathApp/MathApp/MathApp.csproj +++ b/MathApp/MathApp/MathApp.csproj @@ -2,16 +2,16 @@ WinExe - net6.0-windows + net8.0-windows + disable true - enable - enable + disable logo.ico + ttCalculator + ttCalculator - Gelişmiş Matematik & Nümerik Analiz Stüdyosu + 2.0.0 + ttCalculator + $(DefaultItemExcludes);MathApp.Tests\** - - - - - diff --git a/MathApp/MathApp/Program.cs b/MathApp/MathApp/Program.cs index 60b22fd..8be3f98 100644 --- a/MathApp/MathApp/Program.cs +++ b/MathApp/MathApp/Program.cs @@ -1,18 +1,104 @@ using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; using System.Windows.Forms; namespace MathApp { internal static class Program { + private const string MutexName = @"Global\ttCalculator_SingleInstance_Mutex_v2"; + private static Mutex appMutex; + + [DllImport("user32.dll")] + private static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32.dll")] + private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll")] + private static extern bool IsIconic(IntPtr hWnd); + + private const int SW_RESTORE = 9; + /// /// The main entry point for the application. /// [STAThread] static void Main() { - ApplicationConfiguration.Initialize(); - Application.Run(new MainForm()); + bool createdNew = false; + try + { + appMutex = new Mutex(true, MutexName, out createdNew); + } + catch (UnauthorizedAccessException) + { + // Fallback to Local mutex if Global is restricted + appMutex = new Mutex(true, @"Local\ttCalculator_SingleInstance_Mutex_v2", out createdNew); + } + + if (!createdNew) + { + FocusExistingInstance(); + return; + } + + Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); + Application.ThreadException += (s, e) => + { + MessageBox.Show("Beklenmeyen bir hata oluştu:\n" + e.Exception.Message, "ttCalculator - Hata", MessageBoxButtons.OK, MessageBoxIcon.Error); + }; + + try + { + ApplicationConfiguration.Initialize(); + using (MainForm mainForm = new MainForm()) + { + Application.Run(mainForm); + } + } + finally + { + try + { + appMutex?.ReleaseMutex(); + appMutex?.Dispose(); + } + catch { } + + // Ensure no background threads or handles keep the process alive + Environment.Exit(0); + } + } + + private static void FocusExistingInstance() + { + try + { + Process current = Process.GetCurrentProcess(); + Process[] processes = Process.GetProcessesByName(current.ProcessName); + foreach (Process process in processes) + { + if (process.Id != current.Id && process.MainWindowHandle != IntPtr.Zero) + { + if (IsIconic(process.MainWindowHandle)) + { + ShowWindowAsync(process.MainWindowHandle, SW_RESTORE); + } + SetForegroundWindow(process.MainWindowHandle); + return; + } + } + } + catch { } + + MessageBox.Show( + "ttCalculator zaten çalışıyor!", + "ttCalculator", + MessageBoxButtons.OK, + MessageBoxIcon.Information); } } } diff --git a/MathApp/MathApp/ThemeHelper.cs b/MathApp/MathApp/ThemeHelper.cs index 633b832..1f0e220 100644 --- a/MathApp/MathApp/ThemeHelper.cs +++ b/MathApp/MathApp/ThemeHelper.cs @@ -6,64 +6,147 @@ namespace MathApp { public static class ThemeHelper { - // Color Palette - public static Color DarkBackground = Color.FromArgb(32, 32, 32); - public static Color DarkPanel = Color.FromArgb(45, 45, 48); - public static Color LightText = Color.FromArgb(241, 241, 241); - public static Color AccentBlue = Color.FromArgb(0, 122, 204); - public static Color AccentDarkBlue = Color.FromArgb(14, 99, 156); - public static Color BorderColor = Color.FromArgb(63, 63, 70); + // Modern Dark Slate Color Palette + public static readonly Color DarkBackground = Color.FromArgb(15, 23, 42); // #0F172A Slate 900 + public static readonly Color SidebarBackground = Color.FromArgb(11, 17, 32); // #0B1120 Deep Slate + public static readonly Color CardBackground = Color.FromArgb(30, 41, 59); // #1E293B Slate 800 + public static readonly Color CardHeader = Color.FromArgb(40, 53, 76); // #28354C + public static readonly Color InputBackground = Color.FromArgb(15, 23, 42); // #0F172A Slate 900 + public static readonly Color ButtonSecondary = Color.FromArgb(51, 65, 85); // #334155 Slate 700 + public static readonly Color ButtonHover = Color.FromArgb(71, 85, 105); // #475569 Slate 600 + public static readonly Color AccentBlue = Color.FromArgb(14, 165, 233); // #0EA5E9 Sky 500 + public static readonly Color AccentBlueHover = Color.FromArgb(56, 189, 248); // #38BDF8 Sky 400 + public static readonly Color AccentIndigo = Color.FromArgb(99, 102, 241); // #6366F1 Indigo 500 + public static readonly Color LightText = Color.FromArgb(248, 250, 252); // #F8FAFC Slate 50 + public static readonly Color MutedText = Color.FromArgb(148, 163, 184); // #94A3B8 Slate 400 + public static readonly Color BorderColor = Color.FromArgb(51, 65, 85); // #334155 Slate 700 + public static readonly Color DangerRed = Color.FromArgb(239, 68, 68); // #EF4444 Red 500 + public static readonly Color SuccessGreen = Color.FromArgb(16, 185, 129); // #10B981 Emerald 500 + public static readonly Color AmberWarning = Color.FromArgb(245, 158, 11); // #F59E0B Amber 500 public static void ApplyTheme(Form form) { form.BackColor = DarkBackground; form.ForeColor = LightText; - - ApplyRecursively(form.Controls); } - public static void ApplyRecursively(Control.ControlCollection controls) + public static Button CreateActionButton(string text, int width = 160, int height = 38, bool isPrimary = true) { - foreach (Control c in controls) + Button btn = new Button { - if (c is Button btn) - { - btn.FlatStyle = FlatStyle.Flat; - btn.FlatAppearance.BorderSize = 0; - btn.BackColor = DarkPanel; - btn.ForeColor = LightText; - - // Simple hover effect hook if not already handled - // But we don't want to override custom event handlers easily. - // Just set initial properties. - } - else if (c is TextBox txt) - { - txt.BackColor = Color.FromArgb(30, 30, 30); - txt.ForeColor = LightText; - txt.BorderStyle = BorderStyle.FixedSingle; - } - else if (c is Panel pnl) - { - // pnl.BackColor = DarkBackground; // Don't override panel colors if they are structural - // Apply to children - ApplyRecursively(pnl.Controls); - } - else if (c is Label lbl) - { - lbl.ForeColor = LightText; - } - else if (c is GroupBox grp) - { - grp.ForeColor = LightText; - ApplyRecursively(grp.Controls); - } - - if (c.HasChildren && !(c is Panel) && !(c is GroupBox)) - { - ApplyRecursively(c.Controls); - } - } + Text = text, + Size = new Size(width, height), + FlatStyle = FlatStyle.Flat, + BackColor = isPrimary ? AccentBlue : ButtonSecondary, + ForeColor = Color.White, + Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold), + Cursor = Cursors.Hand, + UseVisualStyleBackColor = false + }; + btn.FlatAppearance.BorderSize = 0; + btn.FlatAppearance.MouseOverBackColor = isPrimary ? AccentBlueHover : ButtonHover; + return btn; + } + + public static Button CreateExampleChip(string text) + { + Button btn = new Button + { + Text = text, + AutoSize = true, + MinimumSize = new Size(80, 28), + Padding = new Padding(8, 2, 8, 2), + FlatStyle = FlatStyle.Flat, + BackColor = Color.FromArgb(30, 41, 59), + ForeColor = Color.FromArgb(186, 230, 253), + Font = new Font("Segoe UI", 9F, FontStyle.Regular), + Cursor = Cursors.Hand, + Margin = new Padding(0, 0, 8, 0), + UseVisualStyleBackColor = false + }; + btn.FlatAppearance.BorderSize = 1; + btn.FlatAppearance.BorderColor = Color.FromArgb(56, 189, 248); + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(51, 65, 85); + return btn; + } + + public static Panel CreateHeaderPanel(string title, string subtitle) + { + Panel pnlHeader = new Panel + { + Dock = DockStyle.Top, + Height = 72, + BackColor = Color.FromArgb(15, 23, 42), + Padding = new Padding(24, 12, 24, 8) + }; + + Label lblTitle = new Label + { + Text = title, + Dock = DockStyle.Top, + AutoSize = false, + Height = 30, + Font = new Font("Segoe UI Semibold", 16F, FontStyle.Bold), + ForeColor = LightText, + TextAlign = ContentAlignment.MiddleLeft + }; + + Label lblSub = new Label + { + Text = subtitle, + Dock = DockStyle.Bottom, + AutoSize = false, + Height = 22, + Font = new Font("Segoe UI", 9F, FontStyle.Regular), + ForeColor = MutedText, + TextAlign = ContentAlignment.MiddleLeft + }; + + Panel divider = new Panel + { + Dock = DockStyle.Bottom, + Height = 1, + BackColor = BorderColor + }; + + pnlHeader.Controls.Add(lblSub); + pnlHeader.Controls.Add(lblTitle); + pnlHeader.Controls.Add(divider); + return pnlHeader; + } + + public static Label CreateHintBadge(string text) + { + Label lbl = new Label + { + Text = text, + AutoSize = false, + Font = new Font("Segoe UI", 8.5F, FontStyle.Regular), + ForeColor = Color.FromArgb(186, 230, 253), + BackColor = Color.FromArgb(20, 32, 50), + Padding = new Padding(8, 4, 8, 4), + TextAlign = ContentAlignment.MiddleLeft + }; + return lbl; + } + + public static Button CreateCopyButton(string text = "📋 Sonucu Kopyala") + { + Button btn = new Button + { + Text = text, + AutoSize = true, + Height = 28, + FlatStyle = FlatStyle.Flat, + BackColor = ButtonSecondary, + ForeColor = Color.FromArgb(226, 232, 240), + Font = new Font("Segoe UI", 8.5F), + Cursor = Cursors.Hand, + Padding = new Padding(8, 2, 8, 2) + }; + btn.FlatAppearance.BorderSize = 0; + btn.FlatAppearance.MouseOverBackColor = ButtonHover; + return btn; } } } diff --git a/MathApp/MathApp/logo.ico b/MathApp/MathApp/logo.ico index e4daa7226698dd91eb80206c643f21117b8e4756..40600bf18fcbb7c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z8_I8*0BqwD%MV%Ghio>D<=y5Y{=qtnZWoqpbgtz|s+!x&Z<`>q7*k$%a^4QXNgX4< zU5xk6=4`EQ)7*K474>2Ao6|t@B{61lC(FH|d~T;}xa}RJJ(cuWwzS|PO>69qWDHpO zOq1@)qzA3S_!yRP_ZVLEc+Wt-Jc=Z@JB^{h9@fGx^4s&!V7#S`nV=S%@jSc9#~0(h zx@eKKog-4`J>?^dam0}|+NiN-&UmhEO%zGRX-azX30%EuwCd4^p@YAhwA=FnND(d#B^cu73uB-wS&RH zP&-xG{`W3?lKlNmLEp}^sOBzwp8VVd{X1_%;JNbFinc{S1VlgtL_h>YKmYKmYKmYKmYKm n$) tam destek ($U \cdot S \cdot V^T = A$). +* **Matris Aritmetiği:** Toplama, çıkarma, matris çarpımı, eleman bazlı çarpma/bölme, skaler çarpım. +* **Matris Analizi:** Determinant, İz (Trace), Rank, 1-Norm, 2-Norm, Sonsuz-Norm, Frobenius Normu, Kondisyon Sayısı. +* **Matris Denklem Çözümü:** $A \cdot X = B$ ve $A^T \cdot X = B$. + +### 8. 🎲 Kombinatorik, Polar Dönüşüm ve Özel Fonksiyonlar +* **Taşmasız Kombinatorik:** $C(n, k)$ ve $P(n, k)$ çarpımsal sadeleştirme ile $52!$ gibi $10^{67}$ değerlerine çıkmadan $C(52, 5) = 2.598.960$ hesaplar. +* **Pascal Üçgeni:** $n$. dereceye kadar binom katsayıları tablosu. +* **Karakter Kombinasyon Üreteci:** Belirtilen alfabeden istenen boyutta tüm dizilimleri türetme. +* **Kartezyen $\leftrightarrow$ Polar Dönüşüm:** Hipotenüs ve açı hesabı ($r, \theta$ rad ve derece). + +### 9. 📊 Dinamik Fonksiyon & Grafik Çizici +* **Asimptot & Süreksizlik Algılama:** $\tan(x)$ ve $\frac{1}{x^2-1}$ gibi fonksiyonlarda dikey çizgi hataları önleyen eğri parçalama. +* **İnteraktif Tuval:** Fare ile eksen kaydırma (Pan), tekerlek ile yakınlaştırma (Zoom), tıklama ile nokta işaretleme. +* **Otomatik Eksen Ölçekleme (Auto-fit):** Fonksiyon genliğine göre Y eksenini otomatik sığdırma. --- -## 🛠️ Teknolojiler & Proje Yapısı +## 🛡️ Güvenilirlik & Sistem Kararlılığı -* **Unity Engine:** Görsel arayüz ve etkileşimli grafik çizimleri için kullanılmıştır (`Assets` klasörü). -* **.NET C# Core:** Arka plandaki tüm yüksek hassasiyetli matematik, matris ve nümerik yöntem kütüphaneleri C# dilinde yüksek performanslı olarak geliştirilmiştir (`MathApp/MathApp/Core`). -* **Windows Forms (MathApp):** Masaüstü entegrasyonu ve kontrol panelleri için alternatif gelişmiş masaüstü arayüzü sunar. +* **Tek Kopya Çalışma (Single Instance Mutex):** Uygulama arka planda zaten açıkken ikinci kez açıldığında var olan pencere öne getirilir ve odaklanır. +* **Temiz Süreç Sonlandırma (Zero Background Leakage):** Pencere kapatıldığında arka planda hiçbir süreç veya iş parçacığı asılı kalmaz (`Environment.Exit(0)`). +* **Test Doğrulaması:** 1.169 adet birim ve uçtan uca otomatik testin tamamı %100 başarıyla geçmektedir. --- -## 📦 Geliştiriciler İçin Derleme (Build) +## 🛠️ Kaynak Koddan Derleme -Projeyi kendi bilgisayarınızda açıp geliştirmek isterseniz: -1. Depoyu bilgisayarınıza klonlayın: - ```bash - git clone https://github.com/KULLANICI_ADINIZ/ttCalculator.git - ``` -2. **Unity Projesi için:** Unity Hub üzerinden projeyi ekleyin (Unity 2021.3 veya üzeri önerilir). -3. **Masaüstü App için:** `Math.sln` dosyasını **Visual Studio** ile açarak derleyebilirsiniz. +```bash +# Depoyu klonlayın +git clone https://github.com/LilDosto/ttCalculator.git +cd ttCalculator + +# Projeyi derleyin +dotnet build MathApp/MathApp/MathApp.csproj -c Release + +# Tek parça .exe olarak yayımlayın +dotnet publish MathApp/MathApp/MathApp.csproj -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true -o "Release" +``` --- ## 📄 Lisans -Bu proje **MIT Lisansı** altında lisanslanmıştır. Daha fazla bilgi için `LICENSE` dosyasına bakabilirsiniz. +Bu proje [MIT Lisansı](LICENSE) altında lisanslanmıştır.