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 e4daa72..40600bf 100644 Binary files a/MathApp/MathApp/logo.ico and b/MathApp/MathApp/logo.ico differ diff --git a/README.md b/README.md index 66bbaf0..8c646bd 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,111 @@ -# 📐 ttCalculator +# 📐 ttCalculator v2.0.0 -[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -[![Unity Version](https://img.shields.io/badge/Unity-2021.3+-brightgreen.svg)](https://unity.com/) -[![Platform](https://img.shields.io/badge/Platform-Windows-lightgrey.svg)](https://microsoft.com) +[![GitHub release](https://img.shields.io/github/v/release/LilDosto/ttCalculator?color=brightgreen&label=S%C3%BCr%C3%BCm)](https://github.com/LilDosto/ttCalculator/releases) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) +[![.NET](https://img.shields.io/badge/.NET-8.0--windows-purple.svg)](https://dotnet.microsoft.com/) +[![Platform](https://img.shields.io/badge/Platform-Windows%20x64-lightgrey.svg)](https://microsoft.com) -**ttCalculator**, gelişmiş matematiksel analizler, nümerik yöntemler, matris dekompozisyonları, grafik çizimleri ve çok değişkenli hesaplamalar gerçekleştirebilen son derece güçlü ve premium bir matematik uygulamasıdır. Proje hem bir **Unity** görsel arayüzü hem de **Windows Forms (MathApp)** masaüstü arayüzü barındırmaktadır. +**ttCalculator**, 128-bit yüksek hassasiyetli matematik motoru, gelişmiş nümerik yöntemler, matris dekompozisyonları, dinamik grafik çizimleri ve çok değişkenli analizler gerçekleştirebilen modern ve profesyonel bir masaüstü matematik yazılımıdır. + +Tüm matematiksel çekirdek, 1.169 otomatik testten oluşan kapsamlı doğrulama paketinden **%100 başarıyla (0 hata)** geçirilmiş ve son kullanıcıya hazır hale getirilmiştir. --- -## ✨ Özellikler +## 🚀 Hızlı Başlangıç (Kurulumsuz Doğrudan Çalıştırma) -### 1. 🧮 Gelişmiş Matris Hesaplamaları (Matrix Decompositions) -* **LU Ayrımsaması (LU Decomposition)** -* **QR Ayrımsaması (QR Decomposition)** -* **Cholesky Ayrımsaması (Cholesky Decomposition)** -* **Tekil Değer Ayrışımı (Singular Value Decomposition - SVD)** -* **Özdeğer & Özvektör Hesaplama (Eigenvalue & Eigenvector)** +Uygulamanın hazır derlenmiş Windows sürümünü (`ttCalculator.exe`) hemen çalıştırmak için: -### 2. 📈 Fonksiyon ve Grafik Çizimi (Graph Plotting) -* Dinamik fonksiyon tanımlama ve analitik değerlendirme. -* 2D/3D grafik çizim kontrolleri ile görselleştirme. - -### 3. 🔍 Nümerik Yöntemler & Denklem Çözücüler (Numerical Methods) -* **Kök Bulma (Root Finder):** Gelişmiş nümerik algoritmalar ile karmaşık denklemlerin köklerini hassas bir şekilde bulur. -* **Denklem Sistemleri Çözücü (System Solver):** Çok bilinmeyenli denklem sistemlerinin matris tabanlı çözümü. -* **Taylor Serisi Açılımı (Taylor Series):** Tek değişkenli ve çok değişkenli fonksiyonlar için dinamik Taylor serisi açılımları ve yaklaşım grafikleri. +1. **[Releases](https://github.com/LilDosto/ttCalculator/releases/tag/v2.0.0)** sayfasına gidin. +2. **`ttCalculator.exe`** (veya `ttCalculator-v2.0.0-win-x64.zip`) dosyasını indirin. +3. Çift tıklayarak doğrudan çalıştırın — ek bağımlılık gerektirmez! --- -## 🚀 Kurulum ve Çalıştırma (.EXE) +## ✨ v2.0.0 Temel Özellikleri & Modüller -Uygulamanın hazır derlenmiş Windows sürümünü (`ttCalculator.exe`) çalıştırmak son derece kolaydır: +Uygulama modern koyu tema (Dark Theme) arayüzü ile 9 ana modülden oluşmaktadır: -1. Bu GitHub deposunun sağ tarafındaki **[Releases](https://github.com)** (Sürümler) bölümüne gidin. -2. En son yayınlanan sürümün altındaki **`ttCalculator.exe`** (veya sıkıştırılmış `Math.zip`) dosyasını indirin. -3. İndirdiğiniz dosyayı çalıştırarak gelişmiş matematik motorunu anında deneyimleyin! +### 1. 🔢 Basit & Bilimsel Hesap Makinesi +* **128-Bit Yüksek Hassasiyet:** Standart IEEE-754 çift duyarlılık kayıpları yerine tam hassasiyetli `decimal` aritmetik. +* **Açı Modu (RAD / DEG):** Tek tıkla Radyan / Derece birimi değişimi. +* **Kapsamlı Fonksiyon Desteği:** `sin`, `cos`, `tan`, `cot`, `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh`, `tanh`, `ln`, `log10`, `log(x, base)`, `exp`, `sqrt`, `cbrt`, `abs`, `max`, `min`. +* **Kullanıcı Kolaylıkları:** Otomatik parantez tamamlama, geçmiş (history) paneli ve çift tıklamayla geri yükleme, klavye kısayolları. + +### 2. 🔍 Tek Değişkenli Kök Bulucu (Root Finder) +* **Newton-Raphson Yöntemi:** $f(x) / f'(x)$ teğet tabanlı hızlı yakınsama. +* **Bisection (İkiye Bölme):** Garantili yakınsama ve uç nokta kök tespiti ($f(a)=0$ veya $f(b)=0$). +* **Secant (Kiriş):** İki başlangıç noktası üzerinden türevsiz yaklaşım. +* **Regula Falsi (Illinois Hızlandırmalı):** Dışbükey fonksiyonlardaki durgunluk (stagnation) sorununu çözen Illinois algoritması. +* **Dinamik Değişken Desteği:** $x, t, y$ veya istenen herhangi bir değişken adıyla kök bulma. + +### 3. 📉 Sayısal & Kısmi Türev Hesaplayıcı +* **Farklı Türev Formülleri:** Merkezi sonlu farklar ($O(h^4)$ ve $O(h^6)$ hassasiyet), İleri Binom ve Geri Sonlu Farklar. +* **1. ile 12. Derece Arası Türev:** Yüksek mertebeli türevler için optimize edilmiş adım büyüklüğü ($h$) ve koşullandırma. +* **Çok Değişkenli Kısmi Türev:** İstenen değişkene göre kısmi türev alma ($f(x, y, z)$). + +### 4. 📜 Taylor Serisi Açılımı (Tek Değişkenli) +* İstenen merkez noktası ($a$) etrafında $n$. dereceden sembolik Taylor polinom açılımı. +* Noktadaki türevler ve terim katsayıları tablosu. + +### 5. 🌐 Çok Değişkenli Taylor Serisi +* $f(x, y)$, $f(x, y, z)$ fonksiyonlarının $(x_0, y_0, \dots)$ noktası etrafında çok değişkenli polinom yaklaşımı. +* Sayısal türev kalıntılarını filtreleyen rasyonel katsayı yakalama algoritması. + +### 6. ⚖️ Doğrusal & Doğrusal Olmayan Denklem Sistemleri +* **LU Ayrışımı (A = P·L·U):** Doğrusal sistemler için doğrudan en hızlı çözücü. +* **Ters Matris ($X = A^{-1} \cdot b$):** Analitik ters matris çarpımı. +* **QR Ayrışımı ($Q \cdot R \cdot X = b$):** Householder ortogonal dönüşümü. +* **Gauss-Seidel İterasyonu:** Köşegen baskınlık denetimli ardışık iteratif çözücü. +* **Çok Boyutlu Newton-Raphson:** Doğrusal olmayan (polinom, trigonometrik, üstel vb.) karmaşık sistem çözücü. +* **Doğrusallık Denetimi:** Lineer çözücüye non-lineer denklem verildiğinde otomatik uyarı. + +### 7. 🧮 Gelişmiş Matris Hesaplayıcı & 5 Temel Ayrışım +* **5 Temel Dekompozisyon:** + * **LU Ayrışımı:** $L \cdot U = P \cdot A$ + * **QR Ayrışımı:** $Q \cdot R = A$ + * **Cholesky Ayrışımı:** $L \cdot L^T = A$ (Pozitif tanımlı denetimi) + * **Özdeğer & Özvektör:** $\det(A - \lambda I) = 0$ + * **Tekil Değer Ayrışımı (SVD):** Kare ($n \times n$) ve Dikdörtgen ($m \times n$, $m < n$ ve $m > 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.