v2.0.0: Complete mathematical overhaul, new controls, zero-leak background process, single instance lock, and 100% verified math engine

This commit is contained in:
LilDosto 2026-10-28 01:16:35 +03:00
parent 183da57ea7
commit 72e2fcf145
52 changed files with 10997 additions and 6029 deletions

47
.gitignore vendored
View file

@ -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/

View file

@ -1,7 +1,7 @@
using System;
using System;
/// <summary>
/// Analogy of Syatem.Math class for decimal types
/// Analogy of System.Math class for decimal types with high precision.
/// </summary>
public static class DecimalMath
{
@ -11,14 +11,14 @@ public static class DecimalMath
public const decimal PI = 3.14159265358979323846264338327950288419716939937510M;
/// <summary>
/// represents PI
/// represents machine epsilon for decimal comparisons
/// </summary>
public const decimal Epsilon = 0.0000000000000000001M;
/// <summary>
/// represents 2*PI
/// </summary>
private const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M;
public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M;
/// <summary>
/// represents E
@ -28,12 +28,12 @@ public static class DecimalMath
/// <summary>
/// represents PI/2
/// </summary>
private const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M;
public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M;
/// <summary>
/// represents PI/4
/// </summary>
private const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M;
public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M;
/// <summary>
/// represents 1.0/E
@ -66,48 +66,45 @@ public static class DecimalMath
private const int MaxIteration = 100;
/// <summary>
/// Analogy of Math.Exp method
/// Analogy of Math.Exp method with full precision across all ranges
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Pow method
/// </summary>
/// <param name="value"></param>
/// <param name="pow"></param>
/// <returns></returns>
public static decimal Pow(decimal value, decimal pow)
{
if (pow == Zero) return One;
@ -116,91 +113,74 @@ 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)
// Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5
decimal invPow = One / pow;
if (IsInteger(invPow))
{
int powerInt = (int)pow;
return PowerN(value, powerInt);
}
if (isPowerInteger && value < Zero)
int q = (int)decimal.Round(invPow);
if (q % 2 != 0)
{
int powerInt = (int)pow;
if (powerInt % 2 == 0)
{
return Exp(pow * Log(-value));
}
return -Exp(pow * Log(-value));
}
}
throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır.");
}
if (isPowerInteger)
{
int powerInt = (int)decimal.Round(pow);
return PowerN(value, powerInt);
}
return Exp(pow * Log(value));
}
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;
}
/// <summary>
/// Power to the integer value
/// </summary>
/// <param name="value"></param>
/// <param name="power"></param>
/// <returns></returns>
public static decimal PowerN(decimal value, int power)
{
while (true)
{
if (power == Zero) return One;
if (power < Zero)
if (power == 0) return One;
if (power < 0)
{
value = One / value;
power = -power;
continue;
}
var q = power;
var prod = One;
var current = value;
int q = power;
decimal prod = One;
decimal 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
prod = current * prod;
q--;
}
current *= current; // value^i -> value^(2*i)
current *= current;
q >>= 1;
}
return prod;
}
}
/// <summary>
/// Analogy of Math.Log10
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static decimal Log10(decimal x)
{
return Log(x) * Log10Inv;
@ -209,15 +189,13 @@ public static class DecimalMath
/// <summary>
/// Analogy of Math.Log
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
}
/// <summary>
/// Analogy of Math.Cos
/// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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)
if (x > PI) x -= PIx2;
else if (x < -PI) x += PIx2;
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++)
{
return -Cos(x - PI);
cachedSum = sum;
term *= -x2 / ((2 * i) * (2 * i + 1));
sum += term;
if (sum == cachedSum) break;
}
if (x >= -PIx2 && x <= -PI)
{
return -Cos(x + PI);
return sum;
}
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++)
/// <summary>
/// Analogy of Math.Cos
/// </summary>
public static decimal Cos(decimal x)
{
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;
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 y;
return sum;
}
/// <summary>
/// Analogy of Math.Tan
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Helper function for calculating sin(x) from cos(x)
/// </summary>
/// <param name="x"></param>
/// <param name="cos"></param>
/// <returns></returns>
private static decimal CalculateSinFromCos(decimal x, decimal cos)
{
var moduleOfSin = Sqrt(One - (cos * cos));
var sineIsPositive = IsSignOfSinePositive(x);
if (sineIsPositive) return moduleOfSin;
return -moduleOfSin;
}
/// <summary>
/// Analogy of Math.Sin
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Truncates to [-2*PI;2*PI]
/// </summary>
/// <param name="x"></param>
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));
}
/// <summary>
/// Analogy of Math.Sqrt
/// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation)
/// </summary>
/// <param name="x"></param>
/// <param name="epsilon">lasts iteration while error less than this epsilon</param>
/// <returns></returns>
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;
}
/// <summary>
/// Analogy of Math.Sinh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
/// <summary>
/// Analogy of Math.Cosh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
/// <summary>
/// Analogy of Math.Sign
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static int Sign(decimal x)
{
return x < Zero ? -1 : (x > Zero ? 1 : 0);
@ -409,109 +372,103 @@ public static class DecimalMath
/// <summary>
/// Analogy of Math.Tanh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Abs
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static decimal Abs(decimal x)
{
if (x <= Zero)
{
return -x;
}
return x;
return x <= Zero ? -x : x;
}
/// <summary>
/// Analogy of Math.Asin
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Analogy of Math.Atan
/// Analogy of Math.Atan (safe against overflow for large x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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));
}
/// <summary>
/// Analogy of Math.Acos
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Atan2
/// for more see this
/// <seealso cref="http://i.imgur.com/TRLjs8R.png"/>
/// </summary>
/// <param name="y"></param>
/// <param name="x"></param>
/// <returns></returns>
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).");
}
}

File diff suppressed because it is too large Load diff

View file

@ -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];
throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır.");
}
bool isAddedK = false, isAddedL = false;
int offsetK = 0, offsetL = 0;
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];
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;
}
// 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<string> equations, List<string> 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<string, decimal> zeroPts = new Dictionary<string, decimal>();
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;
}
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<decimal> _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<List<decimal>> _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();
}
}

View file

@ -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;

View file

@ -4,81 +4,25 @@ using System.Runtime.Serialization;
namespace DotNetMatrix
{
/// <summary>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().
///
/// </summary>
[Serializable]
public class EigenvalueDecomposition : System.Runtime.Serialization.ISerializable
{
#region Class variables
/// <summary>Row and column dimension (square matrix).
/// @serial matrix dimension.
/// </summary>
private int n;
/// <summary>Symmetry flag.
/// @serial internal symmetry flag.
/// </summary>
private bool issymmetric;
/// <summary>Arrays for internal storage of eigenvalues.
/// @serial internal storage of eigenvalues.
/// </summary>
private decimal[] d, e;
/// <summary>Array for internal storage of eigenvectors.
/// @serial internal storage of eigenvectors.
/// </summary>
private decimal[][] V;
/// <summary>Array for internal storage of nonsymmetric Hessenberg form.
/// @serial internal storage of nonsymmetric Hessenberg form.
/// </summary>
private decimal[][] H;
/// <summary>Working storage for nonsymmetric algorithm.
/// @serial working storage for nonsymmetric algorithm.
/// </summary>
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
/// <summary>Check for symmetry, then construct the eigenvalue decomposition</summary>
/// <param name="Arg"> Square matrix
/// </param>
/// <returns> Structure to access D and V.
/// </returns>
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
/// <summary>Return the real parts of the eigenvalues</summary>
/// <returns> real(diag(D))
/// </returns>
virtual public decimal[] RealEigenvalues
{
get
@ -1083,9 +886,6 @@ namespace DotNetMatrix
return d;
}
}
/// <summary>Return the imaginary parts of the eigenvalues</summary>
/// <returns> imag(diag(D))
/// </returns>
virtual public decimal[] ImagEigenvalues
{
get
@ -1093,9 +893,6 @@ namespace DotNetMatrix
return e;
}
}
/// <summary>Return the block diagonal eigenvalue matrix</summary>
/// <returns> D
/// </returns>
virtual public GeneralMatrix D
{
get
@ -1121,21 +918,12 @@ namespace DotNetMatrix
return X;
}
}
#endregion // Public Properties
#region Public Methods
/// <summary>Return the eigenvector matrix</summary>
/// <returns> V
/// </returns>
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)
{
}

View file

@ -3,16 +3,8 @@ using System.Runtime.Serialization;
namespace DotNetMatrix
{
#region Internal Maths utility
internal class Maths
{
/// <summary>
/// sqrt(a^2 + b^2) without under/overflow.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static decimal Hypot(decimal a, decimal b)
{
decimal r;
@ -33,78 +25,13 @@ namespace DotNetMatrix
return r;
}
}
#endregion // Internal Maths utility
/// <summary>.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:
/// <P><UL>
/// <LI>Cholesky Decomposition of symmetric, positive definite matrices.
/// <LI>LU Decomposition of rectangular matrices.
/// <LI>QR Decomposition of rectangular matrices.
/// <LI>Singular Value Decomposition of rectangular matrices.
/// <LI>Eigenvalue Decomposition of both symmetric and nonsymmetric square matrices.
/// </UL>
/// <DL>
/// <DT><B>Example of use:</B></DT>
/// <P>
/// <DD>Solve a linear system A x = b and compute the residual norm, ||b - A x||.
/// <P><PRE>
/// 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();
/// </PRE></DD>
/// </DL>
/// </summary>
/// <author>
/// The MathWorks, Inc. and the National Institute of Standards and Technology.
/// </author>
/// <version> 5 August 1998
/// </version>
[Serializable]
public class GeneralMatrix : System.ICloneable, System.Runtime.Serialization.ISerializable, System.IDisposable
{
#region Class variables
/// <summary>Array for internal storage of elements.
/// @serial internal array storage.
/// </summary>
private decimal[][] A;
/// <summary>Row and column dimensions.
/// @serial row dimension.
/// @serial column dimension.
/// </summary>
private int m, n;
#endregion // Class variables
#region Constructors
/// <summary>Construct an m-by-n matrix of zeros. </summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
public GeneralMatrix(int m, int n)
{
this.m = m;
@ -116,14 +43,6 @@ namespace DotNetMatrix
}
}
/// <summary>Construct an m-by-n constant matrix.</summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
/// <param name="s"> Fill the matrix with this scalar value.
/// </param>
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
}
}
/// <summary>Construct a matrix from a 2-D array.</summary>
/// <param name="A"> Two-dimensional array of decimals.
/// </param>
/// <exception cref="System.ArgumentException"> All rows must have the same length
/// </exception>
/// <seealso cref="Create">
/// </seealso>
public GeneralMatrix(decimal[][] A)
{
m = A.Length;
@ -164,14 +72,6 @@ namespace DotNetMatrix
this.A = A;
}
/// <summary>Construct a matrix quickly without checking arguments.</summary>
/// <param name="A"> Two-dimensional array of decimals.
/// </param>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
public GeneralMatrix(decimal[][] A, int m, int n)
{
this.A = A;
@ -179,14 +79,6 @@ namespace DotNetMatrix
this.n = n;
}
/// <summary>Construct a matrix from a one-dimensional packed array</summary>
/// <param name="vals">One-dimensional array of decimals, packed by columns (ala Fortran).
/// </param>
/// <param name="m"> Number of rows.
/// </param>
/// <exception cref="System.ArgumentException"> Array length must be a multiple of m.
/// </exception>
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
/// <summary>Access the internal two-dimensional array.</summary>
/// <returns> Pointer to the two-dimensional array of matrix elements.
/// </returns>
virtual public decimal[][] Array
public virtual decimal[][] Array
{
get
{
return A;
}
}
/// <summary>Copy the internal two-dimensional array.</summary>
/// <returns> Two-dimensional array copy of matrix elements.
/// </returns>
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;
}
}
/// <summary>Make a one-dimensional column packed copy of the internal array.</summary>
/// <returns> Matrix elements packed in a one-dimensional array by columns.
/// </returns>
virtual public decimal[] ColumnPackedCopy
public virtual decimal[] ColumnPackedCopy
{
get
{
@ -262,13 +137,9 @@ namespace DotNetMatrix
}
return vals;
}
}
/// <summary>Make a one-dimensional row packed copy of the internal array.</summary>
/// <returns> Matrix elements packed in a one-dimensional array by rows.
/// </returns>
virtual public decimal[] RowPackedCopy
public virtual decimal[] RowPackedCopy
{
get
{
@ -284,10 +155,7 @@ namespace DotNetMatrix
}
}
/// <summary>Get row dimension.</summary>
/// <returns> m, the number of rows.
/// </returns>
virtual public int RowDimension
public virtual int RowDimension
{
get
{
@ -295,27 +163,15 @@ namespace DotNetMatrix
}
}
/// <summary>Get column dimension.</summary>
/// <returns> n, the number of columns.
/// </returns>
virtual public int ColumnDimension
public virtual int ColumnDimension
{
get
{
return n;
}
}
#endregion // Public Properties
#region Public Methods
/// <summary>Construct a matrix from a copy of a 2-D array.</summary>
/// <param name="A"> Two-dimensional array of decimals.
/// </param>
/// <exception cref="System.ArgumentException"> All rows must have the same length
/// </exception>
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;
}
/// <summary>Make a deep copy of a matrix</summary>
public virtual GeneralMatrix Copy()
{
GeneralMatrix X = new GeneralMatrix(m, n);
@ -351,35 +205,11 @@ namespace DotNetMatrix
return X;
}
/// <summary>Get a single element.</summary>
/// <param name="i"> Row index.
/// </param>
/// <param name="j"> Column index.
/// </param>
/// <returns> A(i,j)
/// </returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public virtual decimal GetElement(int i, int j)
{
return A[i][j];
}
/// <summary>Get a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <returns> A(i0:i1,j0:j1)
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
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;
}
/// <summary>Get a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <returns> A(r(:),c(:))
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual GeneralMatrix GetMatrix(int[] r, int[] c)
{
GeneralMatrix X = new GeneralMatrix(r.Length, c.Length);
@ -432,18 +252,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>Get a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <returns> A(i0:i1,c(:))
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
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;
}
/// <summary>Get a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <returns> A(r(:),j0:j1)
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
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;
}
/// <summary>Set a single element.</summary>
/// <param name="i"> Row index.
/// </param>
/// <param name="j"> Column index.
/// </param>
/// <param name="s"> A(i,j).
/// </param>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public virtual void SetElement(int i, int j, decimal s)
{
A[i][j] = s;
}
/// <summary>Set a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <param name="X"> A(i0:i1,j0:j1)
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int i0, int i1, int j0, int j1, GeneralMatrix X)
{
try
@ -545,16 +317,6 @@ namespace DotNetMatrix
}
}
/// <summary>Set a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <param name="X"> A(r(:),c(:))
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int[] r, int[] c, GeneralMatrix X)
{
try
@ -573,18 +335,6 @@ namespace DotNetMatrix
}
}
/// <summary>Set a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <param name="X"> A(r(:),j0:j1)
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int[] r, int j0, int j1, GeneralMatrix X)
{
try
@ -603,18 +353,6 @@ namespace DotNetMatrix
}
}
/// <summary>Set a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <param name="X"> A(i0:i1,c(:))
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int i0, int i1, int[] c, GeneralMatrix X)
{
try
@ -633,10 +371,6 @@ namespace DotNetMatrix
}
}
/// <summary>Matrix transpose.</summary>
/// <returns> A'
/// </returns>
public virtual GeneralMatrix Transpose()
{
GeneralMatrix X = new GeneralMatrix(n, m);
@ -651,10 +385,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>One norm</summary>
/// <returns> maximum column sum.
/// </returns>
public virtual decimal Norm1()
{
decimal f = 0;
@ -670,19 +400,6 @@ namespace DotNetMatrix
return f;
}
/// <summary>Two norm</summary>
/// <returns> maximum singular value.
/// </returns>
public virtual decimal Norm2()
{
return (new SingularValueDecomposition(this).Norm2());
}
/// <summary>Infinity norm</summary>
/// <returns> maximum row sum.
/// </returns>
public virtual decimal NormInf()
{
decimal f = 0;
@ -698,10 +415,6 @@ namespace DotNetMatrix
return f;
}
/// <summary>Frobenius norm</summary>
/// <returns> sqrt of sum of squares of all elements.
/// </returns>
public virtual decimal NormF()
{
decimal f = 0;
@ -715,10 +428,6 @@ namespace DotNetMatrix
return f;
}
/// <summary>Unary minus</summary>
/// <returns> -A
/// </returns>
public virtual GeneralMatrix UnaryMinus()
{
GeneralMatrix X = new GeneralMatrix(m, n);
@ -733,12 +442,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>C = A + B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A + B
/// </returns>
public virtual GeneralMatrix Add(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -754,12 +457,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>A = A + B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A + B
/// </returns>
public virtual GeneralMatrix AddEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -773,12 +470,6 @@ namespace DotNetMatrix
return this;
}
/// <summary>C = A - B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A - B
/// </returns>
public virtual GeneralMatrix Subtract(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -794,12 +485,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>A = A - B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A - B
/// </returns>
public virtual GeneralMatrix SubtractEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -813,12 +498,6 @@ namespace DotNetMatrix
return this;
}
/// <summary>Element-by-element multiplication, C = A.*B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.*B
/// </returns>
public virtual GeneralMatrix ArrayMultiply(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -834,12 +513,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>Element-by-element multiplication in place, A = A.*B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.*B
/// </returns>
public virtual GeneralMatrix ArrayMultiplyEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -853,12 +526,6 @@ namespace DotNetMatrix
return this;
}
/// <summary>Element-by-element right division, C = A./B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A./B
/// </returns>
public virtual GeneralMatrix ArrayRightDivide(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -874,12 +541,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>Element-by-element right division in place, A = A./B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A./B
/// </returns>
public virtual GeneralMatrix ArrayRightDivideEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -893,12 +554,6 @@ namespace DotNetMatrix
return this;
}
/// <summary>Element-by-element left division, C = A.\B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.\B
/// </returns>
public virtual GeneralMatrix ArrayLeftDivide(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -914,12 +569,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>Element-by-element left division in place, A = A.\B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.\B
/// </returns>
public virtual GeneralMatrix ArrayLeftDivideEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
@ -933,12 +582,6 @@ namespace DotNetMatrix
return this;
}
/// <summary>Multiply a matrix by a scalar, C = s*A</summary>
/// <param name="s"> scalar
/// </param>
/// <returns> s*A
/// </returns>
public virtual GeneralMatrix Multiply(decimal s)
{
GeneralMatrix X = new GeneralMatrix(m, n);
@ -953,12 +596,6 @@ namespace DotNetMatrix
return X;
}
/// <summary>Multiply a matrix by a scalar in place, A = s*A</summary>
/// <param name="s"> scalar
/// </param>
/// <returns> replace A by s*A
/// </returns>
public virtual GeneralMatrix MultiplyEquals(decimal s)
{
for (int i = 0; i < m; i++)
@ -971,14 +608,6 @@ namespace DotNetMatrix
return this;
}
/// <summary>Linear algebraic matrix multiplication, A * B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> Matrix product, A * B
/// </returns>
/// <exception cref="System.ArgumentException"> Matrix inner dimensions must agree.
/// </exception>
public virtual GeneralMatrix Multiply(GeneralMatrix B)
{
if (B.m != n)
@ -1008,160 +637,76 @@ namespace DotNetMatrix
return X;
}
#region Operator Overloading
/// <summary>
/// Addition of matrices
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
public static GeneralMatrix operator +(GeneralMatrix m1, GeneralMatrix m2)
{
return m1.Add(m2);
}
/// <summary>
/// Subtraction of matrices
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
public static GeneralMatrix operator -(GeneralMatrix m1, GeneralMatrix m2)
{
return m1.Subtract(m2);
}
/// <summary>
/// Multiplication of matrices
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
public static GeneralMatrix operator *(GeneralMatrix m1, GeneralMatrix m2)
{
return m1.Multiply(m2);
}
#endregion //Operator Overloading
/// <summary>LU Decomposition</summary>
/// <returns> LUDecomposition
/// </returns>
/// <seealso cref="LUDecomposition">
/// </seealso>
public virtual LUDecomposition LUD()
{
return new LUDecomposition(this);
}
/// <summary>QR Decomposition</summary>
/// <returns> QRDecomposition
/// </returns>
/// <seealso cref="QRDecomposition">
/// </seealso>
public virtual QRDecomposition QRD()
{
return new QRDecomposition(this);
}
/// <summary>Cholesky Decomposition</summary>
/// <returns> CholeskyDecomposition
/// </returns>
/// <seealso cref="CholeskyDecomposition">
/// </seealso>
public virtual CholeskyDecomposition chol()
{
return new CholeskyDecomposition(this);
}
/// <summary>Singular Value Decomposition</summary>
/// <returns> SingularValueDecomposition
/// </returns>
/// <seealso cref="SingularValueDecomposition">
/// </seealso>
public virtual SingularValueDecomposition SVD()
{
return new SingularValueDecomposition(this);
}
/// <summary>Eigenvalue Decomposition</summary>
/// <returns> EigenvalueDecomposition
/// </returns>
/// <seealso cref="EigenvalueDecomposition">
/// </seealso>
public virtual EigenvalueDecomposition Eigen()
{
return new EigenvalueDecomposition(this);
}
/// <summary>Solve A*X = B</summary>
/// <param name="B"> right hand side
/// </param>
/// <returns> solution if A is square, least squares solution otherwise
/// </returns>
public virtual GeneralMatrix Solve(GeneralMatrix B)
{
return (m == n ? (new LUDecomposition(this)).Solve(B):(new QRDecomposition(this)).Solve(B));
}
/// <summary>Solve X*A = B, which is also A'*X' = B'</summary>
/// <param name="B"> right hand side
/// </param>
/// <returns> solution if A is square, least squares solution otherwise.
/// </returns>
public virtual GeneralMatrix SolveTranspose(GeneralMatrix B)
{
return Transpose().Solve(B.Transpose());
}
/// <summary>Matrix inverse or pseudoinverse</summary>
/// <returns> inverse(A) if A is square, pseudoinverse otherwise.
/// </returns>
public virtual GeneralMatrix Inverse()
{
return Solve(Identity(m, m));
}
/// <summary>GeneralMatrix determinant</summary>
/// <returns> determinant
/// </returns>
public virtual decimal Determinant()
{
return new LUDecomposition(this).Determinant();
}
/// <summary>GeneralMatrix rank</summary>
/// <returns> effective numerical rank, obtained from SVD.
/// </returns>
public virtual int Rank()
{
return new SingularValueDecomposition(this).Rank();
}
/// <summary>Matrix condition (2 norm)</summary>
/// <returns> ratio of largest to smallest singular value.
/// </returns>
public virtual decimal Condition()
{
return new SingularValueDecomposition(this).Condition();
}
/// <summary>Matrix trace.</summary>
/// <returns> sum of the diagonal elements.
/// </returns>
public virtual decimal Trace()
{
decimal t = 0;
@ -1172,38 +717,6 @@ namespace DotNetMatrix
return t;
}
/// <summary>Generate matrix with random elements</summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
/// <returns> An m-by-n matrix with uniformly distributed random elements.
/// </returns>
/*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;
}*/
/// <summary>Generate identity matrix</summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
/// <returns> An m-by-n matrix with ones on the diagonal and zeros elsewhere.
/// </returns>
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
/// <summary>Check if size(A) == size(B) *</summary>
private void CheckMatrixDimensions(GeneralMatrix B)
{
if (B.m != m || B.n != n)
@ -1231,65 +738,28 @@ namespace DotNetMatrix
throw new System.ArgumentException("GeneralMatrix dimensions must agree.");
}
}
#endregion // Private Methods
#region Implement IDisposable
/// <summary>
/// Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="disposing"></param>
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);
}
/// <summary>
/// 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.
/// </summary>
~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
/// <summary>Clone the GeneralMatrix object.</summary>
public System.Object Clone()
{
return this.Copy();
}
/// <summary>
/// A method called when serializing this class
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}

View file

@ -3,60 +3,28 @@ using System.Runtime.Serialization;
namespace DotNetMatrix
{
/// <summary>Singular Value Decomposition.
/// <P>
/// 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'.
/// <P>
/// The singular values, sigma[k] = S[k][k], are ordered so that
/// sigma[0] >= sigma[1] >= ... >= sigma[n-1].
/// <P>
/// 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.
/// </summary>
[Serializable]
public class SingularValueDecomposition : System.Runtime.Serialization.ISerializable
{
#region Class variables
/// <summary>Arrays for internal storage of U and V.
/// @serial internal storage of U.
/// @serial internal storage of V.
/// </summary>
private decimal[][] U, V;
/// <summary>Array for internal storage of singular values.
/// @serial internal storage of singular values.
/// </summary>
private decimal[] s;
/// <summary>Row and column dimensions.
/// @serial row dimension.
/// @serial column dimension.
/// </summary>
private int m, n;
#endregion //Class variables
#region Constructor
/// <summary>Construct the singular value decomposition</summary>
/// <param name="Arg"> Rectangular matrix
/// </param>
/// <returns> Structure to access U, S and V.
/// </returns>
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<p
// kase = 2 if s(k) is negligible and k<p
// kase = 3 if e[k-1] is negligible, k<p, and
// s(k), ..., s(p) are not negligible (qr step).
// kase = 4 if e(p-1) is negligible (convergence).
for (k = p - 2; 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
/// <summary>Return the one-dimensional array of singular values</summary>
/// <returns> diagonal of S.
/// </returns>
virtual public decimal[] SingularValues
{
get
@ -575,18 +462,16 @@ namespace DotNetMatrix
}
}
/// <summary>Return the diagonal matrix of singular values</summary>
/// <returns> S
/// </returns>
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
/// <summary>Return the left singular vectors</summary>
/// <returns> U
/// </returns>
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));
}
/// <summary>Return the right singular vectors</summary>
/// <returns> V
/// </returns>
public virtual GeneralMatrix GetV()
{
return new GeneralMatrix(V, n, n);
return new GeneralMatrix(V, n, System.Math.Min(m, n));
}
/// <summary>Two norm</summary>
/// <returns> max(S)
/// </returns>
public virtual decimal Norm2()
{
return s[0];
}
/// <summary>Two norm condition number</summary>
/// <returns> max(S)/min(S)
/// </returns>
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;
}
/// <summary>Effective numerical matrix rank</summary>
/// <returns> Number of nonnegligible singular values.
/// </returns>
public virtual int Rank()
{
decimal eps = (decimal)System.Math.Pow(2.0f, - 52.0f);
@ -653,9 +516,7 @@ namespace DotNetMatrix
}
return r;
}
#endregion //Public Methods
// A method called when serializing this class.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}

File diff suppressed because it is too large Load diff

View file

@ -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

View file

@ -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;
}
}
}

View file

@ -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;
}
}
}
}

View file

@ -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;
}
}

View file

@ -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<VariableInputRow> partialRows = new List<VariableInputRow>();
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<string, decimal> pts = new Dictionary<string, decimal>();
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<string> gradParts = new List<string>();
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;
}
}
}
}

View file

@ -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.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.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.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.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 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.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.lblMinX.Location = new Point(296, y + 4);
this.txtMinX.Location = new System.Drawing.Point(xPos, yPos-3);
this.txtMinX.Size = new System.Drawing.Size(50, 23);
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.Size = new Size(920, 660);
this.pnlControls.ResumeLayout(false);
this.pnlGraphConfig.ResumeLayout(false);
this.pnlGraphConfig.PerformLayout();
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;
}
}

View file

@ -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<PointF> points = new List<PointF>();
private List<PointF> markedPoints = new List<PointF>(); // Points marked by user
private List<List<PointF>> segments = new List<List<PointF>>();
private List<PointF> markedPoints = new List<PointF>();
// Logical ranges
private float rangeMinX = -10;
private float rangeMaxX = 10;
private float rangeMinY = -10;
private float rangeMaxY = 10;
private float rangeMinX = -10f;
private float rangeMaxX = 10f;
private float rangeMinY = -6f;
private float rangeMaxY = 6f;
private string currentEq = "";
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();
// 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(); };
// Enable double buffering
SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
UpdateStyles();
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); } };
// Attach mouse events to the canvas panel
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<PointF> currentSegment = new List<PointF>();
float? prevY = null;
bool prevRad = Function.UseRadians;
Function.UseRadians = true;
try
{
decimal val = NumericalMethods.Method_EvaluateFunction(currentEq, "x", (decimal)x);
for (int i = 0; i <= sampleCount; i++)
{
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<PointF>();
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<PointF>();
}
currentSegment.Add(new PointF(x, y));
prevY = y;
if (Math.Abs(y) < 500f)
{
if (y < tempMinY) tempMinY = y;
if (y > tempMaxY) tempMaxY = y;
}
}
catch
{
// Ignore calculation errors (e.g. division by zero, out of domain)
if (currentSegment.Count > 1) segments.Add(currentSegment);
currentSegment = new List<PointF>();
prevY = null;
}
}
}
finally
{
Function.UseRadians = prevRad;
}
// 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 (currentSegment.Count > 1)
{
segments.Add(currentSegment);
}
if (autoFitY)
{
if (tempMinY < tempMaxY)
{
float h = tempMaxY - tempMinY;
if (h == 0) h = 10;
rangeMinY = tempMinY - h * 0.1f;
rangeMaxY = tempMaxY + h * 0.1f;
if (h < 1e-3f) h = 4f;
rangeMinY = tempMinY - h * 0.18f;
rangeMaxY = tempMaxY + h * 0.18f;
}
else
{
rangeMinY = -10;
rangeMaxY = 10;
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;
float zoom = (e.Delta > 0) ? 0.85f : 1.18f;
// Calculate center
float rangeW = rangeMaxX - rangeMinX;
float rangeH = rangeMaxY - rangeMinY;
if (rangeW < 1e-4f && zoom < 1f) return;
if (rangeW > 1e6f && zoom > 1f) return;
float midX = (rangeMaxX + rangeMinX) / 2;
float midY = (rangeMaxY + rangeMinY) / 2;
float midX = (rangeMaxX + rangeMinX) / 2f;
float midY = (rangeMaxY + rangeMinY) / 2f;
// Apply zoom centered
float halfW = (rangeW * zoom) / 2;
float halfH = (rangeH * zoom) / 2;
float halfW = (rangeW * zoom) / 2f;
float halfH = (rangeH * zoom) / 2f;
rangeMinX = midX - halfW;
rangeMaxX = midX + halfW;
rangeMinY = midY - halfH;
rangeMaxY = midY + halfH;
GeneratePoints();
pnlCanvas.Invalidate();
txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture);
txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture);
base.OnMouseWheel(e); // Let it bubble if needed
GeneratePoints(false);
pnlCanvas.Invalidate();
}
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,19 +247,24 @@ 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);
@ -168,59 +273,62 @@ namespace MathApp.Controls
rangeMinY += moveY;
rangeMaxY += moveY;
lastMousePos = e.Location;
txtMinX.Text = rangeMinX.ToString("0.##", CultureInfo.InvariantCulture);
txtMaxX.Text = rangeMaxX.ToString("0.##", CultureInfo.InvariantCulture);
// 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();
lastMousePos = e.Location;
GeneratePoints(false);
}
pnlCanvas.Invalidate();
}
}
private void PnlCanvas_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragging = false;
Cursor = Cursors.Default;
}
}
private void PnlCanvas_MouseClick(object sender, MouseEventArgs e)
if (!didMoveMouse && compiledFn != null)
{
// 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;
// Snap marked point onto the function curve at clicked X!
float w = Math.Max(1, pnlCanvas.Width);
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);
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.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<PointF> screenPoints = new List<PointF>();
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<PointF> screenPoints = new List<PointF>(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());
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)
{
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);
if (sx < -50 || sx > w + 50 || sy < -50 || sy > h + 50) continue;
// 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);
g.FillEllipse(markBrush, sx - 4, sy - 4, 8, 8);
g.DrawEllipse(markPen, sx - 6, sy - 6, 12, 12);
// Draw coordinates text
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<float, float> mapX, Func<float, float> 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
if (stepW > 0)
{
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.##"), font, brush, sx + 2, h - 20);
g.DrawString(x.ToString("0.##", CultureInfo.InvariantCulture), font, brush, sx + 3, h - 20);
}
}
// Horizontal Grid Lines
if (stepH > 0)
{
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.##"), font, brush, 5, sy - 15);
g.DrawString(y.ToString("0.##", CultureInfo.InvariantCulture), font, brush, 6, sy - 16);
}
}
}
}
private float CalculateStep(float range, int targetSteps)
{
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.5) return 1 * mag;
if (normStep < 3.5) return 2 * mag;
if (normStep < 7.5) return 5 * mag;
return 10 * 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)

View file

@ -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;
}
}
}

View file

@ -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;
}
}
}
}

View file

@ -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;
}
}

View file

@ -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
{
@ -16,14 +17,48 @@ namespace MathApp.Controls
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)
@ -43,7 +78,13 @@ 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<string, decimal> points = new Dictionary<string, decimal>();
@ -52,16 +93,16 @@ namespace MathApp.Controls
string v = row.Variable;
if (string.IsNullOrWhiteSpace(v)) continue;
decimal p = 0;
if(!decimal.TryParse(row.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out p))
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))
{
txtResult.Text = "Duplicate variable: " + v;
txtResult.Text = $"❌ '{v}' değişkeni birden fazla kez eklenmiş.";
return;
}
points.Add(v, p);
@ -69,25 +110,38 @@ namespace MathApp.Controls
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);
bool prevRad = Function.UseRadians;
Function.UseRadians = true;
string result;
try
{
result = NumericalMethods.MethodMultiVar_TaylorSeries(eq, degree, points);
}
finally
{
Function.UseRadians = prevRad;
}
// Formatting clean up
result = result.Replace("+ -", "- ").Replace("+-", "- ").Replace("*", " * ");
string varsList = string.Join(", ", points.Keys);
string centerList = string.Join(", ", points.Select(kv => $"{kv.Key}₀={kv.Value}"));
txtResult.Text = result;
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);
Panel = new Panel
{
Size = new Size(520, 34),
BackColor = ThemeHelper.CardBackground,
Margin = new Padding(0, 0, 0, 5)
};
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 lblVar = new Label
{
Text = "Değişken:",
Location = new Point(10, 8),
AutoSize = true,
ForeColor = ThemeHelper.LightText,
Font = new Font("Segoe UI", 9.5F)
};
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 };
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
};
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 };
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);

View file

@ -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.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.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.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.lblVariable, "Değişken:", new Point(495, 69));
StyleInput(this.txtVariable, "x", new Point(565, 66), new Size(60, 26));
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);
// 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));
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.lblMinX, "Alt Sınır (a):", new Point(14, 102));
StyleInput(this.txtMinX, "1", new Point(140, 99), new Size(110, 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;
StyleLabel(this.lblMaxX, "Üst Sınır (b):", new Point(270, 102));
StyleInput(this.txtMaxX, "2", new Point(360, 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.lblIterations, "Maks. İterasyon:", new Point(495, 102));
StyleInput(this.txtIterations, "50", new Point(610, 99), new Size(65, 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);
// 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;
}
}

View file

@ -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";
int idx = cmbMethod.SelectedIndex;
bool isSinglePoint = (idx == 0); // Newton-Raphson
lblInitialPoint.Visible = !isBracket;
txtInitialPoint.Visible = !isBracket;
lblInitialPoint.Visible = isSinglePoint;
txtInitialPoint.Visible = isSinglePoint;
lblMinX.Visible = isBracket;
txtMinX.Visible = isBracket;
lblMaxX.Visible = isBracket;
txtMaxX.Visible = isBracket;
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();
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;
}
List<string> logs = new List<string>();
string variable = string.IsNullOrWhiteSpace(txtVariable.Text) ? "x" : txtVariable.Text.Trim();
if (!int.TryParse(txtIterations.Text.Trim(), out int iterCount) || iterCount < 1)
iterCount = 50;
if (method == "Newton-Raphson")
int idx = cmbMethod.SelectedIndex;
List<string> 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 (method == "Bisection")
else if (idx == 1) // Bisection
{
decimal minX = decimal.Parse(txtMinX.Text);
decimal maxX = decimal.Parse(txtMaxX.Text);
logs = NumericalMethods.Method_Bisection(eq, minX, maxX, iterCount);
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 (method == "Secant")
else if (idx == 2) // Secant
{
decimal minX = decimal.Parse(txtMinX.Text);
decimal maxX = decimal.Parse(txtMaxX.Text);
logs = NumericalMethods.Method_Secant(eq, minX, maxX, iterCount);
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 if (method == "Regula Falsi")
else // Regula Falsi
{
decimal minX = decimal.Parse(txtMinX.Text);
decimal maxX = decimal.Parse(txtMaxX.Text);
logs = NumericalMethods.Method_RegulaFalsi(eq, minX, maxX, iterCount);
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
}
finally
{
logs = new List<string> { 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;
}
}
}

View file

@ -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;
}
}

View file

@ -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
pnlButtons.Controls.Clear();
pnlButtons.ColumnCount = 6;
pnlButtons.RowCount = 7;
pnlButtons.ColumnStyles.Clear();
pnlButtons.RowStyles.Clear();
this.pnlButtons.RowCount = 5;
this.pnlButtons.RowStyles.Clear();
for(int i=0; i<5; i++) this.pnlButtons.RowStyles.Add(new RowStyle(SizeType.Percent, 20F));
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[] gridLayout = {
"C", "(", ")", "/",
"7", "8", "9", "*",
"4", "5", "6", "-",
"1", "2", "3", "+",
"0", ".", "DEL", "="
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 bool IsOperator(string text)
private string FormatButtonLabel(string token)
{
return text == "+" || text == "-" || text == "*" || text == "/";
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 == "/" || text == "^" || text == "%";
}
// --- Keyboard Support ---
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// Map keys
string input = "";
bool handled = true;
@ -110,7 +231,7 @@ namespace MathApp.Controls
case Keys.D9: input = "9"; break;
case Keys.Add:
case Keys.Oemplus: // Careful with Shift+=
case Keys.Oemplus:
input = "+"; break;
case Keys.Subtract:
case Keys.OemMinus:
@ -118,7 +239,7 @@ namespace MathApp.Controls
case Keys.Multiply:
input = "*"; break;
case Keys.Divide:
case Keys.OemQuestion: // /
case Keys.OemQuestion:
input = "/"; break;
case Keys.Decimal:
@ -134,18 +255,13 @@ namespace MathApp.Controls
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 = ")";
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
private string BalanceParentheses(string expr)
{
return text == "+" || text == "-" || text == "*" || text == "/";
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;
}
}
}

View file

@ -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:";
// 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.numEqCount.Location = new System.Drawing.Point(180, yObject);
this.numEqCount.Minimum = 1;
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.numEqCount.BackColor = Color.FromArgb(15, 23, 42);
this.numEqCount.ForeColor = Color.White;
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.btnGenerate.Location = new Point(562, 8);
this.pnlEquations.Location = new System.Drawing.Point(20, yObject);
this.pnlEquations.Size = new System.Drawing.Size(750, 300);
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;
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);
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.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;
}
}

View file

@ -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);
Panel p = new Panel
{
Size = new Size(820, 36),
BackColor = ThemeHelper.CardBackground,
Margin = new Padding(0, 0, 0, 4)
};
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 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)
};
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 };
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 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 };
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<string> eqs = new List<string>();
Dictionary<string, decimal> dict = new Dictionary<string, decimal>();
for(int i=0; i<equationsInputs.Count; i++)
for (int i = 0; i < count; i++)
{
eqs.Add(equationsInputs[i].Text);
decimal val = 0;
if (decimal.TryParse(initialPointsInputs[i].Text, out val)) { }
string eq = equationsInputs[i].Text.Trim();
if (string.IsNullOrWhiteSpace(eq))
{
txtSystemResult.Text = $"⚠️ Lütfen {i + 1}. denklemi doldurunuz.";
lblHeroSolution.Text = "Eksik Denklem";
lblHeroSolution.ForeColor = Color.FromArgb(239, 68, 68);
return;
}
eqs.Add(eq);
string varName = variablesInputs[i].Text.Trim();
if(string.IsNullOrEmpty(varName)) continue;
if (string.IsNullOrWhiteSpace(varName))
{
txtSystemResult.Text = $"⚠️ Lütfen {i + 1}. denklemin değişken adını giriniz.";
return;
}
string initStr = initialPointsInputs[i].Text.Trim().Replace(',', '.');
if (!decimal.TryParse(initStr, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val))
{
txtSystemResult.Text = $"⚠️ '{varName}' için geçerli bir başlangıç sayısı giriniz.";
return;
}
if (dict.ContainsKey(varName))
{
txtSystemResult.Text = "Error: Duplicate variable '" + varName + "'.";
txtSystemResult.Text = $"❌ Hata: '{varName}' değişkeni birden fazla kez tanımlanmış.";
return;
}
dict.Add(varName, val);
}
int iterCount = 100;
int.TryParse(txtSystemIterations.Text, out iterCount);
if (!int.TryParse(txtSystemIterations.Text.Trim(), out int iterCount) || iterCount < 1)
iterCount = 50;
Dictionary<string, decimal> results = NumericalMethods.MethodMultiVar_SolveEquationSystem(eqs, dict, iterCount);
int methodIdx = cmbSolverMethod.SelectedIndex;
bool prevRad = Function.UseRadians;
Function.UseRadians = true;
Dictionary<string, decimal> results;
List<string> 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;
}
if (results != null)
{
List<string> resLines = new List<string>();
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;
}
}
}

View file

@ -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.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.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.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):";
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;
}
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;
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.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.lblVariable, "Değişken:", new Point(445, 16));
StyleInput(this.txtVariable, "x", new Point(510, 13), new Size(50, 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.lblCenterPoint, "Merkez (a):", new Point(575, 16));
StyleInput(this.txtCenterPoint, "0", new Point(650, 13), new Size(60, 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.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;
this.txtResult.ReadOnly = true;
this.txtResult.ScrollBars = ScrollBars.Vertical;
this.txtResult.Font = new Font("Consolas", 9.5F);
//
// 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.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;
}
}

View file

@ -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;
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 variable = string.IsNullOrWhiteSpace(txtVariable.Text) ? "x" : txtVariable.Text.Trim();
int degree = (int)numOrder.Value;
decimal center = decimal.Parse(txtCenterPoint.Text);
string result = NumericalMethods.Method_TaylorSeries(eq, degree, variable, center);
// Clean up result for display if needed
result = result.Replace("+ -", "- ").Replace("+-", "- ");
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;
}
txtResult.Text = "Taylor Series approximation for f(x) =" + Environment.NewLine +
result;
bool prevRad = Function.UseRadians;
Function.UseRadians = true;
string series;
List<string> derivLines = new List<string>();
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);
}
}
}

View file

@ -1,26 +1,24 @@
using System;
/// <summary>
/// Analogy of System.Math class for decimal types
/// Analogy of System.Math class for decimal types with high precision.
/// </summary>
public static class DecimalMath
{
/* ... (Content from original file, confirmed no Unity deps) ... */
/// <summary>
/// represents PI
/// </summary>
public const decimal PI = 3.14159265358979323846264338327950288419716939937510M;
/// <summary>
/// represents PI
/// represents machine epsilon for decimal comparisons
/// </summary>
public const decimal Epsilon = 0.0000000000000000001M;
/// <summary>
/// represents 2*PI
/// </summary>
private const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M;
public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M;
/// <summary>
/// represents E
@ -30,12 +28,12 @@ public static class DecimalMath
/// <summary>
/// represents PI/2
/// </summary>
private const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M;
public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M;
/// <summary>
/// represents PI/4
/// </summary>
private const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M;
public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M;
/// <summary>
/// represents 1.0/E
@ -68,48 +66,45 @@ public static class DecimalMath
private const int MaxIteration = 100;
/// <summary>
/// Analogy of Math.Exp method
/// Analogy of Math.Exp method with full precision across all ranges
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Pow method
/// </summary>
/// <param name="value"></param>
/// <param name="pow"></param>
/// <returns></returns>
public static decimal Pow(decimal value, decimal pow)
{
if (pow == Zero) return One;
@ -118,91 +113,74 @@ 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)
// Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5
decimal invPow = One / pow;
if (IsInteger(invPow))
{
int powerInt = (int)pow;
return PowerN(value, powerInt);
}
if (isPowerInteger && value < Zero)
int q = (int)decimal.Round(invPow);
if (q % 2 != 0)
{
int powerInt = (int)pow;
if (powerInt % 2 == 0)
{
return Exp(pow * Log(-value));
}
return -Exp(pow * Log(-value));
}
}
throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır.");
}
if (isPowerInteger)
{
int powerInt = (int)decimal.Round(pow);
return PowerN(value, powerInt);
}
return Exp(pow * Log(value));
}
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;
}
/// <summary>
/// Power to the integer value
/// </summary>
/// <param name="value"></param>
/// <param name="power"></param>
/// <returns></returns>
public static decimal PowerN(decimal value, int power)
{
while (true)
{
if (power == Zero) return One;
if (power < Zero)
if (power == 0) return One;
if (power < 0)
{
value = One / value;
power = -power;
continue;
}
var q = power;
var prod = One;
var current = value;
int q = power;
decimal prod = One;
decimal 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
prod = current * prod;
q--;
}
current *= current; // value^i -> value^(2*i)
current *= current;
q >>= 1;
}
return prod;
}
}
/// <summary>
/// Analogy of Math.Log10
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static decimal Log10(decimal x)
{
return Log(x) * Log10Inv;
@ -211,15 +189,13 @@ public static class DecimalMath
/// <summary>
/// Analogy of Math.Log
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
}
/// <summary>
/// Analogy of Math.Cos
/// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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)
if (x > PI) x -= PIx2;
else if (x < -PI) x += PIx2;
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++)
{
return -Cos(x - PI);
cachedSum = sum;
term *= -x2 / ((2 * i) * (2 * i + 1));
sum += term;
if (sum == cachedSum) break;
}
if (x >= -PIx2 && x <= -PI)
{
return -Cos(x + PI);
return sum;
}
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++)
/// <summary>
/// Analogy of Math.Cos
/// </summary>
public static decimal Cos(decimal x)
{
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;
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 y;
return sum;
}
/// <summary>
/// Analogy of Math.Tan
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Helper function for calculating sin(x) from cos(x)
/// </summary>
/// <param name="x"></param>
/// <param name="cos"></param>
/// <returns></returns>
private static decimal CalculateSinFromCos(decimal x, decimal cos)
{
var moduleOfSin = Sqrt(One - (cos * cos));
var sineIsPositive = IsSignOfSinePositive(x);
if (sineIsPositive) return moduleOfSin;
return -moduleOfSin;
}
/// <summary>
/// Analogy of Math.Sin
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Truncates to [-2*PI;2*PI]
/// </summary>
/// <param name="x"></param>
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));
}
/// <summary>
/// Analogy of Math.Sqrt
/// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation)
/// </summary>
/// <param name="x"></param>
/// <param name="epsilon">lasts iteration while error less than this epsilon</param>
/// <returns></returns>
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;
}
/// <summary>
/// Analogy of Math.Sinh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
/// <summary>
/// Analogy of Math.Cosh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
/// <summary>
/// Analogy of Math.Sign
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static int Sign(decimal x)
{
return x < Zero ? -1 : (x > Zero ? 1 : 0);
@ -411,109 +372,103 @@ public static class DecimalMath
/// <summary>
/// Analogy of Math.Tanh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Abs
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static decimal Abs(decimal x)
{
if (x <= Zero)
{
return -x;
}
return x;
return x <= Zero ? -x : x;
}
/// <summary>
/// Analogy of Math.Asin
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Analogy of Math.Atan
/// Analogy of Math.Atan (safe against overflow for large x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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));
}
/// <summary>
/// Analogy of Math.Acos
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Atan2
/// for more see this
/// <seealso cref="http://i.imgur.com/TRLjs8R.png"/>
/// </summary>
/// <param name="y"></param>
/// <param name="x"></param>
/// <returns></returns>
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).");
}
}

File diff suppressed because it is too large Load diff

View file

@ -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];
throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır.");
}
bool isAddedK = false, isAddedL = false;
int offsetK = 0, offsetL = 0;
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];
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;
}
// 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<string> equations, List<string> 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
// Use numerical evaluation to extract exact linear coefficients reliably:
// f(0, 0, ...) = c
// f(0, ..., x_k=1, ..., 0) - c = coeff_k
Dictionary<string, decimal> zeroPts = new Dictionary<string, decimal>();
foreach (string v in variables) zeroPts[v] = 0m;
for (int k = 0; k < variables.Count; k++)
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<decimal> _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<List<decimal>> _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();
}
}

View file

@ -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;

View file

@ -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++)
{

View file

@ -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()

File diff suppressed because it is too large Load diff

View file

@ -1,37 +1,211 @@
$ErrorActionPreference = "Stop"
Add-Type -AssemblyName System.Drawing
$width = 256
$height = 256
$bmp = New-Object System.Drawing.Bitmap $width, $height
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.Clear([System.Drawing.Color]::FromArgb(30,30,30))
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
$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)
$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
$s = [float]$size / 256.0
# 1. Rounded Square Background
$margin = 12.0 * $s
$rectSize = $size - (2.0 * $margin)
$radius = 54.0 * $s
$d = $radius * 2.0
$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.DrawPolygon($pen, $points)
$g.FillPath($bgBrush, $path)
$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)
# Subtle inner glow / grid lines clipped to rounded rect
$g.SetClip($path)
$iconName = "c:/Users/tolga/Desktop/Math/MathApp/MathApp/logo.ico"
$hicon = $bmp.GetHicon()
$icon = [System.Drawing.Icon]::FromHandle([IntPtr]$hicon)
$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)
}
$fs = [System.IO.File]::OpenWrite($iconName)
$icon.Save($fs)
$fs.Close()
# 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()
Write-Host "Logo created successfully at $iconName"
}
$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()
Write-Host "Multi-resolution ICO and preview PNG generated successfully at $icoPath"

View file

@ -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;
}
}

View file

@ -1,5 +1,6 @@
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MathApp.Controls;
@ -10,14 +11,17 @@ 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();
@ -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);
}
}
}

View file

@ -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;

View file

@ -1,26 +1,24 @@
using System;
/// <summary>
/// Analogy of System.Math class for decimal types
/// Analogy of System.Math class for decimal types with high precision.
/// </summary>
public static class DecimalMath
{
/* ... (Content from original file, confirmed no Unity deps) ... */
/// <summary>
/// represents PI
/// </summary>
public const decimal PI = 3.14159265358979323846264338327950288419716939937510M;
/// <summary>
/// represents PI
/// represents machine epsilon for decimal comparisons
/// </summary>
public const decimal Epsilon = 0.0000000000000000001M;
/// <summary>
/// represents 2*PI
/// </summary>
private const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M;
public const decimal PIx2 = 6.28318530717958647692528676655900576839433879875021M;
/// <summary>
/// represents E
@ -30,12 +28,12 @@ public static class DecimalMath
/// <summary>
/// represents PI/2
/// </summary>
private const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M;
public const decimal PIdiv2 = 1.570796326794896619231321691639751442098584699687552910487M;
/// <summary>
/// represents PI/4
/// </summary>
private const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M;
public const decimal PIdiv4 = 0.785398163397448309615660845819875721049292349843776455243M;
/// <summary>
/// represents 1.0/E
@ -68,48 +66,45 @@ public static class DecimalMath
private const int MaxIteration = 100;
/// <summary>
/// Analogy of Math.Exp method
/// Analogy of Math.Exp method with full precision across all ranges
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Pow method
/// </summary>
/// <param name="value"></param>
/// <param name="pow"></param>
/// <returns></returns>
public static decimal Pow(decimal value, decimal pow)
{
if (pow == Zero) return One;
@ -118,91 +113,74 @@ 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)
// Check if power is reciprocal of an odd integer, e.g. 1/3, 1/5
decimal invPow = One / pow;
if (IsInteger(invPow))
{
int powerInt = (int)pow;
return PowerN(value, powerInt);
}
if (isPowerInteger && value < Zero)
int q = (int)decimal.Round(invPow);
if (q % 2 != 0)
{
int powerInt = (int)pow;
if (powerInt % 2 == 0)
{
return Exp(pow * Log(-value));
}
return -Exp(pow * Log(-value));
}
}
throw new ArgumentException("Geçersiz İşlem: Negatif tabanın çift kökü reel sayılarda tanımsızdır.");
}
if (isPowerInteger)
{
int powerInt = (int)decimal.Round(pow);
return PowerN(value, powerInt);
}
return Exp(pow * Log(value));
}
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;
}
/// <summary>
/// Power to the integer value
/// </summary>
/// <param name="value"></param>
/// <param name="power"></param>
/// <returns></returns>
public static decimal PowerN(decimal value, int power)
{
while (true)
{
if (power == Zero) return One;
if (power < Zero)
if (power == 0) return One;
if (power < 0)
{
value = One / value;
power = -power;
continue;
}
var q = power;
var prod = One;
var current = value;
int q = power;
decimal prod = One;
decimal 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
prod = current * prod;
q--;
}
current *= current; // value^i -> value^(2*i)
current *= current;
q >>= 1;
}
return prod;
}
}
/// <summary>
/// Analogy of Math.Log10
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static decimal Log10(decimal x)
{
return Log(x) * Log10Inv;
@ -211,15 +189,13 @@ public static class DecimalMath
/// <summary>
/// Analogy of Math.Log
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
}
/// <summary>
/// Analogy of Math.Cos
/// Analogy of Math.Sin with direct Taylor series (accurate to 28 decimal digits even for small x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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)
if (x > PI) x -= PIx2;
else if (x < -PI) x += PIx2;
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++)
{
return -Cos(x - PI);
cachedSum = sum;
term *= -x2 / ((2 * i) * (2 * i + 1));
sum += term;
if (sum == cachedSum) break;
}
if (x >= -PIx2 && x <= -PI)
{
return -Cos(x + PI);
return sum;
}
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++)
/// <summary>
/// Analogy of Math.Cos
/// </summary>
public static decimal Cos(decimal x)
{
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;
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 y;
return sum;
}
/// <summary>
/// Analogy of Math.Tan
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Helper function for calculating sin(x) from cos(x)
/// </summary>
/// <param name="x"></param>
/// <param name="cos"></param>
/// <returns></returns>
private static decimal CalculateSinFromCos(decimal x, decimal cos)
{
var moduleOfSin = Sqrt(One - (cos * cos));
var sineIsPositive = IsSignOfSinePositive(x);
if (sineIsPositive) return moduleOfSin;
return -moduleOfSin;
}
/// <summary>
/// Analogy of Math.Sin
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Truncates to [-2*PI;2*PI]
/// </summary>
/// <param name="x"></param>
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));
}
/// <summary>
/// Analogy of Math.Sqrt
/// Analogy of Math.Sqrt (Safe against infinite 1-ULP oscillation)
/// </summary>
/// <param name="x"></param>
/// <param name="epsilon">lasts iteration while error less than this epsilon</param>
/// <returns></returns>
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;
}
/// <summary>
/// Analogy of Math.Sinh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
/// <summary>
/// Analogy of Math.Cosh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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
/// <summary>
/// Analogy of Math.Sign
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static int Sign(decimal x)
{
return x < Zero ? -1 : (x > Zero ? 1 : 0);
@ -411,109 +372,103 @@ public static class DecimalMath
/// <summary>
/// Analogy of Math.Tanh
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Abs
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static decimal Abs(decimal x)
{
if (x <= Zero)
{
return -x;
}
return x;
return x <= Zero ? -x : x;
}
/// <summary>
/// Analogy of Math.Asin
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Analogy of Math.Atan
/// Analogy of Math.Atan (safe against overflow for large x)
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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));
}
/// <summary>
/// Analogy of Math.Acos
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
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);
}
/// <summary>
/// Analogy of Math.Atan2
/// for more see this
/// <seealso cref="http://i.imgur.com/TRLjs8R.png"/>
/// </summary>
/// <param name="y"></param>
/// <param name="x"></param>
/// <returns></returns>
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).");
}
}

View file

@ -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++)
{

File diff suppressed because it is too large Load diff

View file

@ -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];
throw new ArgumentException("Determinant hesabı için matris kare (N x N) olmalıdır.");
}
bool isAddedK = false, isAddedL = false;
int offsetK = 0, offsetL = 0;
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];
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;
}
// 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<string> equations, List<string> 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<string, decimal> zeroPts = new Dictionary<string, decimal>();
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;
}
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<decimal> _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<List<decimal>> _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();
}
}

File diff suppressed because it is too large Load diff

View file

@ -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()

View file

@ -2,16 +2,16 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>disable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<ImplicitUsings>disable</ImplicitUsings>
<ApplicationIcon>logo.ico</ApplicationIcon>
<AssemblyName>ttCalculator</AssemblyName>
<Product>ttCalculator - Gelişmiş Matematik &amp; Nümerik Analiz Stüdyosu</Product>
<Version>2.0.0</Version>
<Company>ttCalculator</Company>
<DefaultItemExcludes>$(DefaultItemExcludes);MathApp.Tests\**</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
<Compile Remove="MathApp.Tests\**" />
<EmbeddedResource Remove="MathApp.Tests\**" />
<None Remove="MathApp.Tests\**" />
</ItemGroup>
</Project>

View file

@ -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;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
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();
Application.Run(new MainForm());
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);
}
}
}

View file

@ -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;
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.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);
btn.FlatAppearance.MouseOverBackColor = isPrimary ? AccentBlueHover : ButtonHover;
return btn;
}
if (c.HasChildren && !(c is Panel) && !(c is GroupBox))
public static Button CreateExampleChip(string text)
{
ApplyRecursively(c.Controls);
}
}
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;
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 51 KiB

121
README.md
View file

@ -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
# 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"
```
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.
---
## 📄 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.