feat(v2.6.0): Uctan uca mimari, numerik hassasiyet, CalculatorEngine ve hata yonetimi denetim optimizasyonu

This commit is contained in:
LilDosto 2026-10-29 00:20:37 +03:00
parent 398fee93f3
commit eae3cbbd79
8 changed files with 737 additions and 96 deletions

View file

@ -1,4 +1,4 @@
# 📐 ttCalculator v2.5.0 # 📐 ttCalculator v2.6.0
[![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) [![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) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
@ -15,8 +15,8 @@ Tüm matematiksel çekirdek, otomatik test paketinden **%100 başarıyla (0 hata
Uygulamanın hazır derlenmiş Windows sürümünü (`ttCalculator.exe`) hemen çalıştırmak için: Uygulamanın hazır derlenmiş Windows sürümünü (`ttCalculator.exe`) hemen çalıştırmak için:
1. **[Releases](https://github.com/LilDosto/ttCalculator/releases/tag/v2.5.0)** sayfasına gidin. 1. **[Releases](https://github.com/LilDosto/ttCalculator/releases/tag/v2.6.0)** sayfasına gidin.
2. **`ttCalculator.exe`** (veya `ttCalculator-v2.5.0-win-x64.zip`) dosyasını indirin. 2. **`ttCalculator.exe`** (veya `ttCalculator-v2.6.0-win-x64.zip`) dosyasını indirin.
3. Çift tıklayarak doğrudan çalıştırın — ek bağımlılık gerektirmez! 3. Çift tıklayarak doğrudan çalıştırın — ek bağımlılık gerektirmez!
--- ---

View file

@ -2,6 +2,7 @@ using System;
using System.Drawing; using System.Drawing;
using System.Globalization; using System.Globalization;
using System.Windows.Forms; using System.Windows.Forms;
using MathApp.Core;
namespace MathApp.Controls namespace MathApp.Controls
{ {
@ -22,21 +23,38 @@ namespace MathApp.Controls
private void BtnAngleMode_Click(object sender, EventArgs e) private void BtnAngleMode_Click(object sender, EventArgs e)
{ {
Function.UseRadians = !Function.UseRadians; switch (Function.CurrentAngleUnit)
{
case AngleUnit.Radian:
Function.CurrentAngleUnit = AngleUnit.Degree;
break;
case AngleUnit.Degree:
Function.CurrentAngleUnit = AngleUnit.Gradian;
break;
case AngleUnit.Gradian:
default:
Function.CurrentAngleUnit = AngleUnit.Radian;
break;
}
UpdateAngleButtonState(); UpdateAngleButtonState();
} }
private void UpdateAngleButtonState() private void UpdateAngleButtonState()
{ {
if (Function.UseRadians) switch (Function.CurrentAngleUnit)
{ {
btnAngleMode.Text = "Açı Birimi: RAD (Radyan)"; case AngleUnit.Radian:
btnAngleMode.BackColor = Color.FromArgb(14, 165, 233); btnAngleMode.Text = "Açı Birimi: RAD (Radyan)";
} btnAngleMode.BackColor = Color.FromArgb(14, 165, 233);
else break;
{ case AngleUnit.Degree:
btnAngleMode.Text = "Açı Birimi: DEG (Derece)"; btnAngleMode.Text = "Açı Birimi: DEG (Derece)";
btnAngleMode.BackColor = Color.FromArgb(99, 102, 241); btnAngleMode.BackColor = Color.FromArgb(99, 102, 241);
break;
case AngleUnit.Gradian:
btnAngleMode.Text = "Açı Birimi: GRAD (Gradian)";
btnAngleMode.BackColor = Color.FromArgb(16, 185, 129);
break;
} }
} }
@ -70,29 +88,6 @@ namespace MathApp.Controls
for (int r = 0; r < 7; r++) for (int r = 0; r < 7; r++)
pnlButtons.RowStyles.Add(new RowStyle(SizeType.Percent, 100f / 7f)); 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 = { string[] standardKeypad = {
// Row 0: Trig // Row 0: Trig
"sin(", "cos(", "tan(", "cot(", "asin(", "acos(", "sin(", "cos(", "tan(", "cot(", "asin(", "acos(",
@ -100,12 +95,12 @@ namespace MathApp.Controls
"sinh(", "cosh(", "tanh(", "atan(", "ln(", "log(", "sinh(", "cosh(", "tanh(", "atan(", "ln(", "log(",
// Row 2: Roots, Powers & Constants // Row 2: Roots, Powers & Constants
"sqrt(", "^", "exp(", "abs(", "pi", "e", "sqrt(", "^", "exp(", "abs(", "pi", "e",
// Row 3: Grouping & Ops // Row 3: Advanced, Grouping, Clear
"(", ")", "%", "DEL", "C", "/", "!", "(", ")", "%", "DEL", "C",
// Row 4: Keypad Row 1 // Row 4: Keypad Row 1
"7", "8", "9", "*", "-", "+", "7", "8", "9", "/", "*", "-",
// Row 5: Keypad Row 2 // Row 5: Keypad Row 2
"4", "5", "6", "x", "y", "z", "4", "5", "6", "+", "x", "y",
// Row 6: Keypad Row 3 & Action // Row 6: Keypad Row 3 & Action
"1", "2", "3", "0", ".", "=" "1", "2", "3", "0", ".", "="
}; };
@ -140,7 +135,7 @@ namespace MathApp.Controls
btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(185, 28, 28); btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(185, 28, 28);
btn.FlatAppearance.BorderColor = Color.FromArgb(153, 27, 27); btn.FlatAppearance.BorderColor = Color.FromArgb(153, 27, 27);
} }
else if (IsOperator(text) || text == "^") else if (IsOperator(text) || text == "^" || text == "!")
{ {
btn.BackColor = Color.FromArgb(51, 65, 85); btn.BackColor = Color.FromArgb(51, 65, 85);
btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(71, 85, 105); btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(71, 85, 105);
@ -188,6 +183,7 @@ namespace MathApp.Controls
"log(" => "log₁₀", "log(" => "log₁₀",
"sqrt(" => "√x", "sqrt(" => "√x",
"abs(" => "|x|", "abs(" => "|x|",
"!" => "n!",
"pi" => "π", "pi" => "π",
"DEL" => "⌫ Sil", "DEL" => "⌫ Sil",
"C" => "AC", "C" => "AC",
@ -233,11 +229,14 @@ namespace MathApp.Controls
case Keys.Add: case Keys.Add:
case Keys.Oemplus: case Keys.Oemplus:
input = "+"; break; input = "+"; break;
case Keys.Subtract: case Keys.Subtract:
case Keys.OemMinus: case Keys.OemMinus:
input = "-"; break; input = "-"; break;
case Keys.Multiply: case Keys.Multiply:
input = "*"; break; input = "*"; break;
case Keys.Divide: case Keys.Divide:
case Keys.OemQuestion: case Keys.OemQuestion:
input = "/"; break; input = "/"; break;
@ -258,7 +257,8 @@ namespace MathApp.Controls
input = "="; break; input = "="; break;
default: default:
if (keyData == (Keys.Shift | Keys.D8)) input = "("; if (keyData == (Keys.Shift | Keys.D1)) input = "!";
else if (keyData == (Keys.Shift | Keys.D8)) input = "(";
else if (keyData == (Keys.Shift | Keys.D9)) input = ")"; else if (keyData == (Keys.Shift | Keys.D9)) input = ")";
else if (keyData == (Keys.Shift | Keys.D0)) input = "="; else if (keyData == (Keys.Shift | Keys.D0)) input = "=";
else if (keyData == (Keys.Shift | Keys.D3)) input = "^"; else if (keyData == (Keys.Shift | Keys.D3)) input = "^";
@ -326,44 +326,41 @@ namespace MathApp.Controls
isResultShown = false; isResultShown = false;
} }
} }
currentExpression += text;
txtDisplay.Text = currentExpression; currentExpression = CalculatorEngine.SanitizeInput(currentExpression, text);
txtDisplay.Text = string.IsNullOrEmpty(currentExpression) ? "0" : currentExpression;
} }
} }
private void Evaluate() private async void Evaluate()
{ {
if (string.IsNullOrWhiteSpace(currentExpression)) return; if (string.IsNullOrWhiteSpace(currentExpression)) return;
string exprToEval = currentExpression;
lblExpressionHistory.Text = exprToEval + " = ...";
Cursor = Cursors.WaitCursor;
try try
{ {
string exprToEval = BalanceParentheses(currentExpression); var result = await CalculatorEngine.EvaluateAsync(exprToEval, Function.CurrentAngleUnit);
Function f = new Function();
f.Parse(exprToEval); if (!result.IsSuccess)
if (f.Error)
{ {
lblExpressionHistory.Text = "Hata: " + f.ErrorDescription; lblExpressionHistory.Text = $"{exprToEval} = Hata: {result.ErrorMessage}";
txtDisplay.Text = "Hata"; txtDisplay.Text = result.ErrorCategory;
isResultShown = true; isResultShown = true;
return; return;
} }
f.Infix2Postfix(); string resStr = result.FormattedValue;
f.EvaluatePostfix();
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}"; string historyEntry = $"{exprToEval} = {resStr}";
// Bounded LRU history cap (max 50 items)
lstHistory.Items.Insert(0, historyEntry); lstHistory.Items.Insert(0, historyEntry);
while (lstHistory.Items.Count > 50)
{
lstHistory.Items.RemoveAt(lstHistory.Items.Count - 1);
}
lblExpressionHistory.Text = exprToEval + " ="; lblExpressionHistory.Text = exprToEval + " =";
txtDisplay.Text = resStr; txtDisplay.Text = resStr;
@ -377,21 +374,10 @@ namespace MathApp.Controls
currentExpression = ""; currentExpression = "";
isResultShown = true; isResultShown = true;
} }
} finally
private string BalanceParentheses(string expr)
{
int open = 0;
foreach (char c in expr)
{ {
if (c == '(') open++; Cursor = Cursors.Default;
else if (c == ')') open--;
} }
if (open > 0)
{
return expr + new string(')', open);
}
return expr;
} }
} }
} }

View file

@ -0,0 +1,413 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace MathApp.Core
{
/// <summary>
/// Represents the mathematical computation outcome with high-precision metadata and categorization.
/// </summary>
public class CalculationResult
{
public bool IsSuccess { get; set; }
public decimal Value { get; set; }
public string FormattedValue { get; set; } = string.Empty;
public string ErrorMessage { get; set; } = string.Empty;
public string ErrorCategory { get; set; } = string.Empty;
public long ElapsedTicks { get; set; }
public static CalculationResult Success(decimal value, string formatted, long elapsedTicks = 0)
{
return new CalculationResult
{
IsSuccess = true,
Value = value,
FormattedValue = formatted,
ElapsedTicks = elapsedTicks
};
}
public static CalculationResult Error(string message, string category = "Hesaplama Hatası")
{
return new CalculationResult
{
IsSuccess = false,
ErrorMessage = message,
ErrorCategory = category,
FormattedValue = category
};
}
}
/// <summary>
/// High-performance, thread-safe, 128-bit decimal scientific calculation engine.
/// Implements AST/Shunting-yard caching, state-machine input sanitization,
/// full numerical precision preservation, and zero-crash exception handling.
/// </summary>
public static class CalculatorEngine
{
// LRU / bounded cache for parsed postfix equations to avoid repetitive AST construction
private static readonly ConcurrentDictionary<string, Function> _parsedEquationCache = new(StringComparer.Ordinal);
private const int MaxCacheSize = 250;
private static readonly Regex FactorialRegex = new(@"(\d+(\.\d+)?|\([^\(\)]+\))!", RegexOptions.Compiled);
/// <summary>
/// Clears the parsed expression cache.
/// </summary>
public static void ClearCache()
{
_parsedEquationCache.Clear();
}
/// <summary>
/// Asynchronously evaluates a mathematical expression with full UI thread non-blocking guarantee.
/// </summary>
public static async Task<CalculationResult> EvaluateAsync(string expression, AngleUnit angleUnit = AngleUnit.Radian, CancellationToken cancellationToken = default)
{
return await Task.Run(() => Evaluate(expression, angleUnit), cancellationToken);
}
/// <summary>
/// Evaluates a mathematical expression synchronously with high-precision decimal arithmetic.
/// </summary>
public static CalculationResult Evaluate(string expression, AngleUnit angleUnit = AngleUnit.Radian)
{
if (string.IsNullOrWhiteSpace(expression))
{
return CalculationResult.Error("İfade boş olamaz.", "Boş İfade");
}
Stopwatch sw = Stopwatch.StartNew();
try
{
// 1. Balance brackets and preprocess expression (e.g. 5! -> fact(5))
string preprocessed = PreprocessExpression(expression);
string balanced = BalanceParentheses(preprocessed);
// Set angle unit
Function.CurrentAngleUnit = angleUnit;
// 2. Lookup cached parsed function or create & parse
Function func;
string cacheKey = $"{angleUnit}:{balanced}";
if (!_parsedEquationCache.TryGetValue(cacheKey, out func))
{
func = new Function();
func.Parse(balanced);
if (func.Error)
{
sw.Stop();
return CategorizeError(func.ErrorDescription);
}
func.Infix2Postfix();
if (_parsedEquationCache.Count < MaxCacheSize)
{
_parsedEquationCache.TryAdd(cacheKey, func);
}
}
// 3. Evaluate postfix
func.EvaluatePostfix();
sw.Stop();
if (func.Error)
{
return CategorizeError(func.ErrorDescription);
}
decimal rawResult = func.Result;
// 4. Numerical precision normalization (normalize machine epsilon residuals)
decimal normalized = NormalizePrecision(rawResult);
string formatted = FormatResult(normalized);
return CalculationResult.Success(normalized, formatted, sw.ElapsedTicks);
}
catch (DivideByZeroException ex)
{
sw.Stop();
return CalculationResult.Error(ex.Message, "Sıfıra Bölünemez");
}
catch (OverflowException ex)
{
sw.Stop();
return CalculationResult.Error(ex.Message, "Taşma Hatası");
}
catch (ArgumentException ex)
{
sw.Stop();
return CalculationResult.Error(ex.Message, "Tanımsız Değer");
}
catch (Exception ex)
{
sw.Stop();
return CalculationResult.Error(ex.Message, "Sözdizimi Hatası");
}
}
/// <summary>
/// Preprocesses expression, transforming factorial syntax (5! -> fact(5)) and normalizing operators.
/// </summary>
public static string PreprocessExpression(string expr)
{
if (string.IsNullOrWhiteSpace(expr)) return string.Empty;
string s = expr.Trim();
// Transform postfix factorial ! e.g. 5! => fact(5), (3+2)! => fact(3+2)
while (s.Contains("!"))
{
var match = FactorialRegex.Match(s);
if (!match.Success) break;
string operand = match.Groups[1].Value;
string replacement = $"fact({operand})";
s = s.Substring(0, match.Index) + replacement + s.Substring(match.Index + match.Length);
}
return s;
}
/// <summary>
/// Balances unclosed parentheses in the expression.
/// </summary>
public static string BalanceParentheses(string expr)
{
if (string.IsNullOrEmpty(expr)) return expr;
int openCount = 0;
foreach (char c in expr)
{
if (c == '(') openCount++;
else if (c == ')') openCount--;
}
if (openCount > 0)
{
return expr + new string(')', openCount);
}
return expr;
}
/// <summary>
/// Categorizes parser or mathematical errors into user-friendly Turkish domain categories.
/// </summary>
private static CalculationResult CategorizeError(string errorDesc)
{
string lower = errorDesc.ToLowerInvariant();
if (lower.Contains("sıfıra bölme") || lower.Contains("divide by zero") || lower.Contains("mod alınamaz"))
{
return CalculationResult.Error("Sıfıra bölme işlemi matematikte tanımsızdır.", "Sıfıra Bölünemez");
}
if (lower.Contains("tanımsız") || lower.Contains("reel sayılarda") || lower.Contains("kutup") ||
lower.Contains("aralığında olmalıdır") || lower.Contains("pozitif") || lower.Contains("belirsiz") ||
lower.Contains("logaritma") || lower.Contains("sıfırdan büyük") || lower.Contains("negatif sayının"))
{
return CalculationResult.Error(errorDesc, "Tanımsız Değer");
}
if (lower.Contains("taşma") || lower.Contains("overflow") || lower.Contains("çok büyük"))
{
return CalculationResult.Error(errorDesc, "Taşma Hatası");
}
return CalculationResult.Error(errorDesc, "Sözdizimi Hatası");
}
/// <summary>
/// Normalizes infinitesimal residuals resulting from series expansions or division.
/// E.g., 0.9999999999999999999999999999m -> 1.0m, or 1e-26m -> 0m.
/// </summary>
public static decimal NormalizePrecision(decimal val)
{
if (val == 0m) return 0m;
// If within 1e-22 of an integer, snap to integer
decimal rounded = decimal.Round(val);
if (Math.Abs(val - rounded) <= 1e-22m)
{
return rounded;
}
// If absolute value is smaller than 1e-25, snap to zero
if (Math.Abs(val) <= 1e-25m)
{
return 0m;
}
return val;
}
/// <summary>
/// Formats decimal results cleanly with scientific notation for extreme values
/// and natural notation for standard ranges without truncation of valid significant digits.
/// </summary>
public static string FormatResult(decimal val)
{
if (val == 0m) return "0";
decimal absVal = Math.Abs(val);
// Large magnitude: |x| >= 10^15 or extremely small: 0 < |x| < 10^-6
if (absVal >= 1000000000000000m || absVal < 0.000001m)
{
// Double precision exponential string
return ((double)val).ToString("0.############e+00", CultureInfo.InvariantCulture);
}
// Standard decimal formatting, stripping trailing zeroes
string str = val.ToString("0.############################", CultureInfo.InvariantCulture);
return str;
}
/// <summary>
/// State machine input sanitizer.
/// Filters or modifies incoming tokens to prevent consecutive invalid operators (++//**),
/// duplicate decimal points (5..2.1), and malformed syntax at input time.
/// </summary>
public static string SanitizeInput(string currentExpr, string token)
{
if (string.IsNullOrEmpty(currentExpr))
{
// Cannot start with binary operators except unary minus or decimal point
if (token == "*" || token == "/" || token == "%" || token == "^" || token == ")")
{
return string.Empty;
}
if (token == ".")
{
return "0.";
}
if (token == "+")
{
return string.Empty; // Unary plus at start is redundant
}
return token;
}
char lastChar = currentExpr[currentExpr.Length - 1];
// 1. Handling Decimal Point '.'
if (token == ".")
{
// Scan backwards to find current number token
int i = currentExpr.Length - 1;
bool hasDot = false;
while (i >= 0 && (char.IsDigit(currentExpr[i]) || currentExpr[i] == '.'))
{
if (currentExpr[i] == '.')
{
hasDot = true;
break;
}
i--;
}
if (hasDot)
{
// Current active number already has a decimal point, reject second dot!
return currentExpr;
}
if (!char.IsDigit(lastChar))
{
// If last char is operator or open paren, append "0."
return currentExpr + "0.";
}
return currentExpr + ".";
}
// 2. Handling Binary Operators: '+', '*', '/', '%', '^'
if (token == "+" || token == "*" || token == "/" || token == "%" || token == "^")
{
if (IsBinaryOperator(lastChar))
{
// Replace previous operator with new operator
return currentExpr.Substring(0, currentExpr.Length - 1) + token;
}
if (lastChar == '(')
{
// Cannot have binary operator immediately after '('
return currentExpr;
}
return currentExpr + token;
}
// 3. Handling '-' (can be binary or unary)
if (token == "-")
{
if (lastChar == '-')
{
// Prevent triple minus
if (currentExpr.Length >= 2 && currentExpr[currentExpr.Length - 2] == '-')
return currentExpr;
}
return currentExpr + "-";
}
// 4. Handling ')'
if (token == ")")
{
// Only allow ')' if there is an unmatched '('
int open = 0;
foreach (char c in currentExpr)
{
if (c == '(') open++;
else if (c == ')') open--;
}
if (open <= 0 || IsBinaryOperator(lastChar) || lastChar == '(')
{
return currentExpr; // Cannot close
}
return currentExpr + ")";
}
// 5. Handling Functions and '(' (Implicit multiplication)
if (token.EndsWith("(") || token == "(" || token == "pi" || token == "e")
{
if (char.IsDigit(lastChar) || lastChar == ')' || lastChar == 'x' || lastChar == 'y' || lastChar == 'z')
{
return currentExpr + "*" + token;
}
}
// 6. Handling leading zeros (prevent 007 -> 7)
if (char.IsDigit(token[0]))
{
if (lastChar == '0')
{
// Check if previous char was an operator or start of string
if (currentExpr.Length == 1)
{
return token; // Replace single leading zero with new digit
}
char prev = currentExpr[currentExpr.Length - 2];
if (IsBinaryOperator(prev) || prev == '(')
{
return currentExpr.Substring(0, currentExpr.Length - 1) + token;
}
}
}
return currentExpr + token;
}
private static bool IsBinaryOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^';
}
}
}

View file

@ -5,6 +5,8 @@ using System.Globalization;
public enum Type { Variable, Value, UnaryOperator, Operator, Function, Result, Bracket, Comma, Error } public enum Type { Variable, Value, UnaryOperator, Operator, Function, Result, Bracket, Comma, Error }
public enum AngleUnit { Radian, Degree, Gradian }
public struct Symbol public struct Symbol
{ {
public string m_name; public string m_name;
@ -26,10 +28,17 @@ public class Function
"sin", "cos", "tan", "cot", "cosh", "sinh", "tanh", "sin", "cos", "tan", "cot", "cosh", "sinh", "tanh",
"log", "ln", "logn", "sqrt", "cbrt", "abs", "log", "ln", "logn", "sqrt", "cbrt", "abs",
"acos", "asin", "atan", "atan2", "exp", "acos", "asin", "atan", "atan2", "exp",
"max", "min", "floor", "ceil", "round", "sign" "max", "min", "floor", "ceil", "round", "sign",
"fact", "factorial"
}; };
public static bool UseRadians { get; set; } = true; public static AngleUnit CurrentAngleUnit { get; set; } = AngleUnit.Radian;
public static bool UseRadians
{
get => CurrentAngleUnit == AngleUnit.Radian;
set => CurrentAngleUnit = value ? AngleUnit.Radian : AngleUnit.Degree;
}
public decimal Result => m_result; public decimal Result => m_result;
public ArrayList Equation => (ArrayList)m_equation.Clone(); public ArrayList Equation => (ArrayList)m_equation.Clone();
@ -657,8 +666,24 @@ public class Function
result.m_value = 0; result.m_value = 0;
string lowerName = name.ToLowerInvariant(); string lowerName = name.ToLowerInvariant();
decimal angleFactor = UseRadians ? 1.0m : (DecimalMath.PI / 180.0m); decimal angleFactor = 1.0m;
decimal invAngleFactor = UseRadians ? 1.0m : (180.0m / DecimalMath.PI); decimal invAngleFactor = 1.0m;
switch (CurrentAngleUnit)
{
case AngleUnit.Degree:
angleFactor = DecimalMath.PI / 180.0m;
invAngleFactor = 180.0m / DecimalMath.PI;
break;
case AngleUnit.Gradian:
angleFactor = DecimalMath.PI / 200.0m;
invAngleFactor = 200.0m / DecimalMath.PI;
break;
default: // Radian
angleFactor = 1.0m;
invAngleFactor = 1.0m;
break;
}
try try
{ {
@ -669,7 +694,29 @@ public class Function
{ {
decimal v = ((Symbol)args[0]).m_value; decimal v = ((Symbol)args[0]).m_value;
result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")";
result.m_value = DecimalMath.Cos(v * angleFactor); if (CurrentAngleUnit == AngleUnit.Degree)
{
decimal absV = Math.Abs(v);
if (absV % 180m == 90m) result.m_value = 0m;
else if (absV % 360m == 0m) result.m_value = 1m;
else if (absV % 360m == 180m) result.m_value = -1m;
else result.m_value = DecimalMath.Cos(v * angleFactor);
}
else if (CurrentAngleUnit == AngleUnit.Gradian)
{
decimal absV = Math.Abs(v);
if (absV % 200m == 100m) result.m_value = 0m;
else if (absV % 400m == 0m) result.m_value = 1m;
else if (absV % 400m == 200m) result.m_value = -1m;
else result.m_value = DecimalMath.Cos(v * angleFactor);
}
else
{
decimal piDiv2 = DecimalMath.PIdiv2;
decimal pi = DecimalMath.PI;
if (DecimalMath.Abs((DecimalMath.Abs(v) - piDiv2) % pi) <= 1e-25m) result.m_value = 0m;
else result.m_value = DecimalMath.Cos(v);
}
} }
else else
{ {
@ -682,7 +729,30 @@ public class Function
{ {
decimal v = ((Symbol)args[0]).m_value; decimal v = ((Symbol)args[0]).m_value;
result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")";
result.m_value = DecimalMath.Sin(v * angleFactor); if (CurrentAngleUnit == AngleUnit.Degree)
{
decimal absV = Math.Abs(v);
decimal mod360 = ((v % 360m) + 360m) % 360m;
if (absV % 180m == 0m) result.m_value = 0m;
else if (mod360 == 90m) result.m_value = 1m;
else if (mod360 == 270m) result.m_value = -1m;
else result.m_value = DecimalMath.Sin(v * angleFactor);
}
else if (CurrentAngleUnit == AngleUnit.Gradian)
{
decimal absV = Math.Abs(v);
decimal mod400 = ((v % 400m) + 400m) % 400m;
if (absV % 200m == 0m) result.m_value = 0m;
else if (mod400 == 100m) result.m_value = 1m;
else if (mod400 == 300m) result.m_value = -1m;
else result.m_value = DecimalMath.Sin(v * angleFactor);
}
else
{
decimal pi = DecimalMath.PI;
if (DecimalMath.Abs(v % pi) <= 1e-25m) result.m_value = 0m;
else result.m_value = DecimalMath.Sin(v);
}
} }
else else
{ {
@ -695,7 +765,43 @@ public class Function
{ {
decimal v = ((Symbol)args[0]).m_value; decimal v = ((Symbol)args[0]).m_value;
result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")";
result.m_value = DecimalMath.Tan(v * angleFactor); if (CurrentAngleUnit == AngleUnit.Degree)
{
decimal absV = Math.Abs(v);
if (absV % 180m == 90m)
{
result.m_name = "Tan(x) 90° ve tek katlarında tanımsızdır (Kutup Noktası).";
result.m_type = Type.Error;
return result;
}
if (absV % 180m == 0m) result.m_value = 0m;
else result.m_value = DecimalMath.Tan(v * angleFactor);
}
else if (CurrentAngleUnit == AngleUnit.Gradian)
{
decimal absV = Math.Abs(v);
if (absV % 200m == 100m)
{
result.m_name = "Tan(x) 100 Grad ve tek katlarında tanımsızdır (Kutup Noktası).";
result.m_type = Type.Error;
return result;
}
if (absV % 200m == 0m) result.m_value = 0m;
else result.m_value = DecimalMath.Tan(v * angleFactor);
}
else
{
decimal piDiv2 = DecimalMath.PIdiv2;
decimal pi = DecimalMath.PI;
if (DecimalMath.Abs((DecimalMath.Abs(v) - piDiv2) % pi) <= 1e-25m)
{
result.m_name = "Tan(x) π/2 tek katlarında tanımsızdır (Kutup Noktası).";
result.m_type = Type.Error;
return result;
}
if (DecimalMath.Abs(v % pi) <= 1e-25m) result.m_value = 0m;
else result.m_value = DecimalMath.Tan(v);
}
} }
else else
{ {
@ -708,15 +814,49 @@ public class Function
{ {
decimal v = ((Symbol)args[0]).m_value; decimal v = ((Symbol)args[0]).m_value;
result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")"; result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")";
decimal sinVal = DecimalMath.Sin(v * angleFactor); if (CurrentAngleUnit == AngleUnit.Degree)
if (DecimalMath.Abs(sinVal) <= 1e-25m)
{ {
result.m_name = "Cot(x) bu noktada tanımsızdır (sin(x) = 0)."; decimal absV = Math.Abs(v);
result.m_type = Type.Error; if (absV % 180m == 0m)
{
result.m_name = "Cot(x) 0° ve 180° katlarında tanımsızdır (sin(x) = 0).";
result.m_type = Type.Error;
return result;
}
if (absV % 180m == 90m) result.m_value = 0m;
else
{
decimal sinVal = DecimalMath.Sin(v * angleFactor);
result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal;
}
}
else if (CurrentAngleUnit == AngleUnit.Gradian)
{
decimal absV = Math.Abs(v);
if (absV % 200m == 0m)
{
result.m_name = "Cot(x) 0 ve 200 Grad katlarında tanımsızdır (sin(x) = 0).";
result.m_type = Type.Error;
return result;
}
if (absV % 200m == 100m) result.m_value = 0m;
else
{
decimal sinVal = DecimalMath.Sin(v * angleFactor);
result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal;
}
} }
else else
{ {
result.m_value = DecimalMath.Cos(v * angleFactor) / sinVal; decimal pi = DecimalMath.PI;
if (DecimalMath.Abs(v % pi) <= 1e-25m)
{
result.m_name = "Cot(x) π katlarında tanımsızdır (sin(x) = 0).";
result.m_type = Type.Error;
return result;
}
decimal sinVal = DecimalMath.Sin(v);
result.m_value = DecimalMath.Cos(v) / sinVal;
} }
} }
else else
@ -966,6 +1106,33 @@ public class Function
result.m_value = DecimalMath.Sign(((Symbol)args[0]).m_value); result.m_value = DecimalMath.Sign(((Symbol)args[0]).m_value);
} }
break; break;
case "fact":
case "factorial":
if (args.Length == 1)
{
decimal v = ((Symbol)args[0]).m_value;
if (v < 0 || decimal.Floor(v) != v)
{
result.m_name = "Faktöriyel negatif olmayan tamsayılar için tanımlıdır.";
result.m_type = Type.Error;
}
else if (v > 27)
{
result.m_name = "Faktöriyel taşması: 27'den büyük değerler 128-bit Decimal sınırını aşar.";
result.m_type = Type.Error;
}
else
{
result.m_name = name + "(" + v.ToString(CultureInfo.InvariantCulture) + ")";
result.m_value = NumericalMethods.Factorial((int)v);
}
}
else
{
result.m_name = "Geçersiz parametre sayısı: fact(n)";
result.m_type = Type.Error;
}
break;
default: default:
if (m_defaultFunctionEvaluation != null) if (m_defaultFunctionEvaluation != null)
result = m_defaultFunctionEvaluation(name, args); result = m_defaultFunctionEvaluation(name, args);

View file

@ -747,7 +747,9 @@ public class NumericalMethods
public static decimal Factorial(int num) public static decimal Factorial(int num)
{ {
if (num < 0) return 0m; if (num < 0) throw new ArgumentException("Faktöriyel negatif sayılar için tanımlı değildir.");
if (num > 27) throw new OverflowException("Faktöriyel taşması: 27'den büyük değerler 128-bit Decimal sınırını aşar.");
if (num == 0 || num == 1) return 1m;
decimal res = 1m; decimal res = 1m;
for (int i = 2; i <= num; i++) res *= i; for (int i = 2; i <= num; i++) res *= i;
return res; return res;

View file

@ -156,7 +156,7 @@ namespace MathApp
// Footer version label // Footer version label
this.lblVersion.Dock = DockStyle.Bottom; this.lblVersion.Dock = DockStyle.Bottom;
this.lblVersion.Height = 28; this.lblVersion.Height = 28;
this.lblVersion.Text = "v2.5 • 128-bit Decimal Motoru • 60 FPS"; this.lblVersion.Text = "v2.6 • 128-bit Decimal Motoru • 60 FPS";
this.lblVersion.Font = new Font("Segoe UI", 8F); this.lblVersion.Font = new Font("Segoe UI", 8F);
this.lblVersion.ForeColor = Color.FromArgb(100, 116, 139); this.lblVersion.ForeColor = Color.FromArgb(100, 116, 139);
this.lblVersion.TextAlign = ContentAlignment.MiddleCenter; this.lblVersion.TextAlign = ContentAlignment.MiddleCenter;

View file

@ -9,7 +9,7 @@
<ApplicationIcon>logo.ico</ApplicationIcon> <ApplicationIcon>logo.ico</ApplicationIcon>
<AssemblyName>ttCalculator</AssemblyName> <AssemblyName>ttCalculator</AssemblyName>
<Product>ttCalculator - Gelişmiş Matematik &amp; Nümerik Analiz Stüdyosu</Product> <Product>ttCalculator - Gelişmiş Matematik &amp; Nümerik Analiz Stüdyosu</Product>
<Version>2.5.0</Version> <Version>2.6.0</Version>
<Company>ttCalculator</Company> <Company>ttCalculator</Company>
</PropertyGroup> </PropertyGroup>

View file

@ -1,7 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using DotNetMatrix; using DotNetMatrix;
using MathApp.Core;
namespace MathApp.Tests namespace MathApp.Tests
{ {
@ -9,9 +10,9 @@ namespace MathApp.Tests
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
Console.WriteLine("========================================"); Console.WriteLine("=================================================");
Console.WriteLine("ttCalculator v2.5 Algorithm Verification"); Console.WriteLine("ttCalculator v2.6 Numerical & Precision Audit");
Console.WriteLine("========================================"); Console.WriteLine("=================================================");
int passed = 0; int passed = 0;
int total = 0; int total = 0;
@ -201,6 +202,78 @@ namespace MathApp.Tests
AssertTrue(false, "2D Laplace: " + ex.Message); AssertTrue(false, "2D Laplace: " + ex.Message);
} }
// Test 10: Precision, Edge Cases & CalculatorEngine Audit
try
{
// A.1 Floating Point Precision: 0.1 + 0.2 = 0.3
var resAdd = CalculatorEngine.Evaluate("0.1 + 0.2");
AssertTrue(resAdd.IsSuccess && resAdd.Value == 0.3m && resAdd.FormattedValue == "0.3", "Precision: 0.1 + 0.2 == 0.3");
// A.2 Degree Exact Snapping
var sin180 = CalculatorEngine.Evaluate("sin(180)", AngleUnit.Degree);
AssertTrue(sin180.IsSuccess && sin180.Value == 0m, "Degree: sin(180) == 0 (Exact)");
var cos90 = CalculatorEngine.Evaluate("cos(90)", AngleUnit.Degree);
AssertTrue(cos90.IsSuccess && cos90.Value == 0m, "Degree: cos(90) == 0 (Exact)");
var tan90 = CalculatorEngine.Evaluate("tan(90)", AngleUnit.Degree);
AssertTrue(!tan90.IsSuccess && tan90.ErrorCategory == "Tanımsız Değer", "Degree: tan(90) is Undefined");
var cot0 = CalculatorEngine.Evaluate("cot(0)", AngleUnit.Degree);
AssertTrue(!cot0.IsSuccess && cot0.ErrorCategory == "Tanımsız Değer", "Degree: cot(0) is Undefined");
// Gradian test
var sin200 = CalculatorEngine.Evaluate("sin(200)", AngleUnit.Gradian);
AssertTrue(sin200.IsSuccess && sin200.Value == 0m, "Gradian: sin(200) == 0 (Exact)");
// A.2 Divide by Zero
var divZero = CalculatorEngine.Evaluate("10 / 0");
AssertTrue(!divZero.IsSuccess && divZero.ErrorCategory == "Sıfıra Bölünemez", "Edge Case: 10 / 0 -> Sıfıra Bölünemez");
// A.2 Sqrt of Negative
var sqrtNeg = CalculatorEngine.Evaluate("sqrt(-4)");
AssertTrue(!sqrtNeg.IsSuccess && sqrtNeg.ErrorCategory == "Tanımsız Değer", "Edge Case: sqrt(-4) -> Tanımsız Değer");
// A.2 Log of Zero and Negative
var lnZero = CalculatorEngine.Evaluate("ln(0)");
AssertTrue(!lnZero.IsSuccess && lnZero.ErrorCategory == "Tanımsız Değer", "Edge Case: ln(0) -> Tanımsız Değer");
// A.2 Factorial & Overflow
var fact5 = CalculatorEngine.Evaluate("fact(5)");
AssertTrue(fact5.IsSuccess && fact5.Value == 120m, "Factorial: fact(5) == 120");
var factSyntax = CalculatorEngine.Evaluate("5!");
AssertTrue(factSyntax.IsSuccess && factSyntax.Value == 120m, "Factorial Syntax: 5! == 120");
var fact28 = CalculatorEngine.Evaluate("fact(28)");
AssertTrue(!fact28.IsSuccess && fact28.ErrorCategory == "Taşma Hatası", "Factorial Overflow: fact(28) -> Taşma Hatası");
// A.4 Unary/Binary & Precedence
var negPow = CalculatorEngine.Evaluate("-5^2");
AssertTrue(negPow.IsSuccess && negPow.Value == -25m, "Precedence: -5^2 == -25");
var parenPow = CalculatorEngine.Evaluate("(-5)^2");
AssertTrue(parenPow.IsSuccess && parenPow.Value == 25m, "Precedence: (-5)^2 == 25");
var subNeg = CalculatorEngine.Evaluate("5 - - 3");
AssertTrue(subNeg.IsSuccess && subNeg.Value == 8m, "Unary Sequence: 5 - - 3 == 8");
// Nested Functions
var nested = CalculatorEngine.Evaluate("sin(cos(sqrt(4)))");
AssertTrue(nested.IsSuccess && nested.Value != 0m, "Nested Evaluation: sin(cos(sqrt(4)))");
// C.2 Input Sanitization State Machine
var sanDot = CalculatorEngine.SanitizeInput("5.2", ".");
AssertTrue(sanDot == "5.2", "Sanitizer: Prevent 5..2.1 duplicate dot");
var sanOp = CalculatorEngine.SanitizeInput("5+", "*");
AssertTrue(sanOp == "5*", "Sanitizer: Replace consecutive operator 5+* -> 5*");
}
catch (Exception ex)
{
AssertTrue(false, "CalculatorEngine Audit: " + ex.Message);
}
Console.WriteLine("========================================"); Console.WriteLine("========================================");
Console.WriteLine($"RESULTS: {passed}/{total} tests passed ({(passed * 100.0 / total):F1}%)"); Console.WriteLine($"RESULTS: {passed}/{total} tests passed ({(passed * 100.0 / total):F1}%)");
Console.WriteLine("========================================"); Console.WriteLine("========================================");