using GraphTUI.Core.Math; namespace GraphTUI.Tests; public static class CalculusTests { public static void Register(TestRunner runner) { runner.Add("Calculus: Numerical Derivative", () => { // d/dx sin(x) at x=0 is cos(0) = 1 double dSin0 = Calculus.Derivative(System.Math.Sin, 0.0); Assert.Within(1.0, dSin0, 1e-4); // d/dx sin(x) at x=pi/3 is cos(pi/3) = 0.5 double dSinPi3 = Calculus.Derivative(System.Math.Sin, System.Math.PI / 3.0); Assert.Within(0.5, dSinPi3, 1e-4); // d/dx (x^3) at x=2 is 3*(2^2) = 12 double dX3 = Calculus.Derivative(x => x * x * x, 2.0); Assert.Within(12.0, dX3, 1e-4); }); runner.Add("Calculus: Tangent Line Equation", () => { // f(x) = x^2 at x0 = 3: slope = 6, y0 = 9 // Line: y = 9 + 6*(x - 3) = 6x - 9 var (slope, y0, line) = Calculus.TangentLine(x => x * x, 3.0); Assert.Within(6.0, slope, 1e-4); Assert.Within(9.0, y0, 1e-4); Assert.Within(9.0, line(3.0), 1e-4); Assert.Within(15.0, line(4.0), 1e-4); }); runner.Add("Calculus: Definite Integral (Simpson's Rule)", () => { // Integral of sin(x) from 0 to pi is 2.0 double intSin = Calculus.DefiniteIntegral(System.Math.Sin, 0.0, System.Math.PI, 100); Assert.Within(2.0, intSin, 1e-4); // Integral of x^2 from 0 to 1 is 1/3 ~ 0.333333 double intX2 = Calculus.DefiniteIntegral(x => x * x, 0.0, 1.0, 100); Assert.Within(1.0 / 3.0, intX2, 1e-4); }); runner.Add("Calculus: Root Finding", () => { // Roots of x^2 - 4 on [-5, 5] should be -2 and 2 var roots = Calculus.FindRoots(x => x * x - 4.0, -5.0, 5.0, 200); Assert.Equal(2, roots.Count); Assert.Within(-2.0, roots[0], 1e-3); Assert.Within(2.0, roots[1], 1e-3); // Roots of x^3 - 3x^2 - x + 3 = (x-1)(x+1)(x-3) var cubicRoots = Calculus.FindRoots(x => x * x * x - 3 * x * x - x + 3, -4.0, 4.0, 300); Assert.Equal(3, cubicRoots.Count); Assert.Within(-1.0, cubicRoots[0], 1e-3); Assert.Within(1.0, cubicRoots[1], 1e-3); Assert.Within(3.0, cubicRoots[2], 1e-3); }); runner.Add("Calculus: Extrema Detection", () => { // f(x) = x^3 - 3x on [-2, 2]: // f'(x) = 3x^2 - 3 = 0 -> x = -1 (local max, y=2), x = 1 (local min, y=-2) var extrema = Calculus.FindExtrema(x => x * x * x - 3 * x, -2.0, 2.0, 300); Assert.Equal(2, extrema.Count); Assert.Equal(ExtremumType.LocalMaximum, extrema[0].Type); Assert.Within(-1.0, extrema[0].X, 1e-3); Assert.Within(2.0, extrema[0].Y, 1e-3); Assert.Equal(ExtremumType.LocalMinimum, extrema[1].Type); Assert.Within(1.0, extrema[1].X, 1e-3); Assert.Within(-2.0, extrema[1].Y, 1e-3); }); } }