Skip to content

Module_Calculus

cyclone_dll edited this page Jul 6, 2026 · 9 revisions

Location: Home / Calculus module


Calculus Module - Calculus Module

The Vorcyc.Mathematics.Calculus namespace provides comprehensive computational tools, including limit calculation, integration, differentiation, Taylor series expansion, Fourier series expansion, Runge–Kutta methods for differential equations, and Newton–Raphson methods for nonlinear equations.

The root namespace for all types in this module is: Vorcyc.Mathematics.Calculus

📒Contents


Vorcyc.Mathematics.Calculus.Limits Class

Vorcyc.Mathematics.Calculus.Limits is a class that provides numerical limit computation, supporting generic floating-point types. It supports computing limits as the input approaches a target point from the left, right, or both sides.

Methods

1. CalculateLimit Method

  • public T CalculateLimit(T a, Direction direction = Direction.Both, int maxSteps = 100, T? tolerance = null, T? h = null)
    • Computes the limit of a function at the specified point.
    • Parameters:
      • a: Target point that the limit approaches.
      • direction: Approach direction; defaults to two-sided.
      • maxSteps: Maximum number of iterations; default is 100.
      • tolerance: Convergence tolerance; default is 1e-10.
      • h: Initial step size; optional, takes precedence over the default step size.
    • Returns: The limit value.
    • Exceptions:
      • ArgumentException: Thrown when parameters are invalid or the limit does not exist.

2. ClearCache Method

  • public void ClearCache()
    • Clears the function value cache for this instance.

Code Example

The following example uses the CalculateLimit method of the Limits class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus;

public class LimitsExample
{
    public static void Main()
    {
        // Define the function
        var limits = new Limits<double>(x => x * x, 1e-5);

        // Compute limits
        double resultLeft = limits.CalculateLimit(2.0, Limits<double>.Direction.Left);
        double resultRight = limits.CalculateLimit(2.0, Limits<double>.Direction.Right);
        double resultBoth = limits.CalculateLimit(2.0, Limits<double>.Direction.Both);

        // Output results
        Console.WriteLine($"Limits Test: Left = {resultLeft}, Right = {resultRight}, Both = {resultBoth}");
    }
}

Vorcyc.Mathematics.Calculus.Integration Class

Vorcyc.Mathematics.Calculus.Integration is a class that provides numerical integration, supporting generic floating-point types.

Methods

1. Constructors

  • public Integration(T defaultH) — Pass the integrand on each integration call.
  • public Integration(SingleVariableFunction<T> func, T defaultH, T lowerBound = default) — Bind the integrand and the lower bound for indefinite integration.

2. Integrate Method

  • public T Integrate(T a, T b, int n, SingleVariableFunction<T> func, T? h = null, Method method = Method.Trapezoidal)
    • Computes the definite integral from a to b.
  • public T Integrate(T a, T b, int n = 1000, Method method = Method.Trapezoidal, T? h = null)
    • Computes the definite integral using the integrand bound at construction time.
    • Parameters:
      • a: Lower integration bound.
      • b: Upper integration bound.
      • n: Number of subintervals; default is 1000.
      • func: Integrand function.
      • h: Step size; optional, takes precedence over the default step size.
      • method: Integration method; supports Trapezoidal, Simpson, Romberg, GaussLegendre, AdaptiveSimpson.
    • Returns: Definite integral value.
    • Exceptions:
      • ArgumentNullException: Thrown when func is null.
      • ArgumentException: Thrown when n is less than 1, h is too small, or the method is not supported.

3. IndefiniteIntegrate / GetIndefiniteIntegral Methods

  • public T IndefiniteIntegrate(T x, int n = 1000, Method method = Method.Trapezoidal) — Numerical indefinite integral F(x)=∫ f(t)dt.
  • public SingleVariableFunction<T> GetIndefiniteIntegral(...) — Returns the indefinite integral function.

4. ClearCache Method

  • public void ClearCache()
    • Clears the function value cache for this instance.

Code Example

The following example uses the Integrate method of the Integration class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus;

public class IntegrationExample
{
    public static void Main()
    {
        // Define the integrand
        var integration = new Integration<double>(1e-5);

        // Compute definite integrals
        double resultTrapezoidal = integration.Integrate(0.0, 1.0, 1000, x => x * x);
        double resultSimpson = integration.Integrate(0.0, 1.0, 1000, x => x * x, method: Integration<double>.Method.Simpson);

        // Output results
        Console.WriteLine($"Integration Test: Trapezoidal = {resultTrapezoidal}, Simpson = {resultSimpson}");
    }
}

Vorcyc.Mathematics.Calculus.Derivative Class

Vorcyc.Mathematics.Calculus.Derivative is a class that computes derivatives and partial derivatives, supporting both numerical methods and automatic differentiation.

Methods

1. Calculate Method

  • public T Calculate(T x, int order = 1, T? h = null, Method method = Method.Central)
    • Computes the derivative of a single-variable function (numerical method).
    • Parameters:
      • x: Point at which to compute the derivative.
      • order: Derivative order; default is 1.
      • h: Step size; default is null.
      • method: Numerical method; default is central difference.
    • Returns: Derivative value.
    • Exceptions:
      • InvalidOperationException: Thrown when this instance does not support numerical single-variable derivative computation.
      • ArgumentException: Thrown when order is less than 1 or the step size is too small.

2. CalculateAD Method

  • public T CalculateAD(T x)
    • Computes the single-variable derivative using automatic differentiation.
    • Parameters:
      • x: Point at which to compute the derivative.
    • Returns: Derivative value.
    • Exceptions:
      • InvalidOperationException: Thrown when this instance does not support single-variable automatic differentiation.

3. Gradient / GradientAD Methods

  • public T[] Gradient(Span<T> point, T? h = null, Method method = Method.Central) — Numerical gradient of a multivariate scalar function.
  • public T[] GradientAD(Span<T> point) — Automatic-differentiation gradient.

4. ClearCache Method

  • public void ClearCache()
    • Clears the cache for this instance.

Code Example

The following example uses the Calculate and CalculateAD methods of the Derivative class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus;

public class DerivativeExample
{
    public static void Main()
    {
        // Define the function
        var derivative = new Derivative<double>(x => x * x, 1e-5);

        // Compute derivatives
        double resultNumeric = derivative.Calculate(2.0);
        var derivativeAD = new Derivative<double>(x => x * x);
        double resultAD = derivativeAD.CalculateAD(2.0);

        // Output results
        Console.WriteLine($"Derivative Test: Numeric = {resultNumeric}, AD = {resultAD}");
    }
}

Vorcyc.Mathematics.Calculus.DualNumber Struct

DualNumber<T> represents a dual number (value, deriv) used for forward-mode automatic differentiation. It supports arithmetic operations and chain-rule extensions for Sin, Cos, Exp, Log, Pow, and Sqrt.

var x = new DualNumber<double>(2.0, 1.0);
double deriv = (x * x).Deriv; // 4
var deriv = new Derivative<double>(DualNumber<double>.Exp);
double dExp = deriv.CalculateAD(1.0); // e

Vorcyc.Mathematics.Calculus.Jacobian Class

Jacobian<T> computes the Jacobian matrix of a vector-valued function f: Rⁿ→Rᵐ.

  • public Matrix<T> Calculate(Span<T> point, T? h = null, Derivative<T>.Method method = Central)

Vorcyc.Mathematics.Calculus.Series.TaylorSeries Class

Vorcyc.Mathematics.Calculus.Series.TaylorSeries is a class that provides Taylor series expansion computation, supporting generic floating-point types.

Methods

1. Calculate Method

  • public T Calculate(T x, int order = 5)
    • Evaluates the Taylor series at the specified point, truncated to the given order.
    • Parameters:
      • x: Evaluation point.
      • order: Maximum order; default is 5.
    • Returns: Taylor series approximation.
    • Exceptions:
      • ArgumentException: Thrown when order is less than 0.

2. GetTaylorCoefficient Method

  • public T GetTaylorCoefficient(int order)
    • Gets the Taylor series coefficient (derivative value divided by factorial).
    • Parameters:
      • order: Order.
    • Returns: The Taylor coefficient of order order.

3. ClearCache Method

  • public void ClearCache()
    • Clears the derivative cache.

Code Example

The following example uses the Calculate method of the TaylorSeries class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus.Series;

public class TaylorSeriesExample
{
    public static void Main()
    {
        // Define the function
        var taylorSeries = new TaylorSeries<double>(x => Math.Exp(x), 0.0, 1e-5);

        // Compute the Taylor series
        double result = taylorSeries.Calculate(1.0, 5);

        // Output result
        Console.WriteLine($"Taylor Series Test: Result = {result}");
    }
}

Vorcyc.Mathematics.Calculus.Series.FourierSeries Class

Vorcyc.Mathematics.Calculus.Series.FourierSeries is a class that provides Fourier series expansion computation, supporting generic floating-point types.

Methods

1. Calculate Method

  • public T Calculate(T x, int order = 5, int segments = 1000)
    • Evaluates the Fourier series at the specified point, truncated to the given order.
    • Parameters:
      • x: Evaluation point.
      • order: Maximum order; default is 5.
      • segments: Number of integration subintervals; default is 1000.
    • Returns: Fourier series approximation.
    • Exceptions:
      • ArgumentException: Thrown when order is less than 0 or segments is less than 1.

2. GetFourierCoefficient Method

  • public T GetFourierCoefficient(bool isCosine, int n, int segments = 1000)
    • Gets a Fourier series coefficient (aₙ or bₙ).
    • Parameters:
      • isCosine: true for cosine coefficient aₙ; false for sine coefficient bₙ.
      • n: Harmonic order.
      • segments: Number of integration subintervals; default is 1000.
    • Returns: The Fourier coefficient of order n.
    • Exceptions:
      • ArgumentException: Thrown when n is less than 0 or segments is less than 1.
      • InvalidOperationException: Thrown when the integration result is invalid.

3. ClearCache Method

  • public void ClearCache()
    • Clears the function value cache for this instance.

Code Example

The following example uses the Calculate method of the FourierSeries class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus.Series;

public class FourierSeriesExample
{
    public static void Main()
    {
        // Define the function
        var fourierSeries = new FourierSeries<double>(x => Math.Sin(x), 2 * Math.PI, 1e-5);

        // Compute the Fourier series
        double result = fourierSeries.Calculate(Math.PI / 2, 5);

        // Output result
        Console.WriteLine($"Fourier Series Test: Result = {result}");
    }
}

Vorcyc.Mathematics.Calculus.NumericalMethods.RungeKutta Class

Vorcyc.Mathematics.Calculus.NumericalMethods.RungeKutta is a class that solves ordinary differential equations using the Runge–Kutta method (RK4), supporting generic floating-point types.

Methods

1. Solve Method

  • public T Solve(T x0, T y0, T xEnd, int steps = 100, T? h = null)
    • Solves a differential equation using fourth-order Runge–Kutta (RK4).
    • Parameters:
      • x0: Initial x value.
      • y0: Initial y value.
      • xEnd: Target x value.
      • steps: Number of steps; determines step size h = (xEnd - x0) / steps.
      • h: Step size; optional, takes precedence over the default step size.
    • Returns: The y value at xEnd.
    • Exceptions:
      • ArgumentException: Thrown when steps is less than 1.

2. ClearCache Method

  • public void ClearCache()
    • Clears the function value cache.

Code Example

The following example uses the Solve method of the RungeKutta class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus.NumericalMethods;

public class RungeKuttaExample
{
    public static void Main()
    {
        // Define the differential equation
        var rungeKutta = new RungeKutta<double>((x, y) => x + y, 1e-5);

        // Solve the differential equation
        double result = rungeKutta.Solve(0.0, 1.0, 1.0, 100);

        // Output result
        Console.WriteLine($"Runge-Kutta Test: Result = {result}");
    }
}

Vorcyc.Mathematics.Calculus.NumericalMethods.RungeKuttaSystem Class

RungeKuttaSystem<T> uses RK4 to solve systems of ordinary differential equations dy/dx = f(x, y).

  • public T[] Solve(T x0, ReadOnlySpan<T> y0, T xEnd, int steps = 100, T? h = null)

Vorcyc.Mathematics.Calculus.NumericalMethods.NewtonRaphson Class

Vorcyc.Mathematics.Calculus.NumericalMethods.NewtonRaphson is a class that solves nonlinear equations f(x) = 0 using the Newton–Raphson method, supporting generic floating-point types.

Methods

1. Solve Method

  • public T Solve(T initialGuess, int maxIterations = 100, T? tolerance = null)
    • Finds a root of f(x) = 0 using the Newton–Raphson method.
    • Parameters:
      • initialGuess: Initial guess.
      • maxIterations: Maximum number of iterations; default is 100.
      • tolerance: Convergence tolerance; default is 1e-10.
    • Returns: Approximate root of the equation.
    • Exceptions:
      • ArgumentException: Thrown when maxIterations is less than 1.
      • InvalidOperationException: Thrown when the derivative is 0 or iteration fails to converge.

Code Example

The following example uses the Solve method of the NewtonRaphson class, with comments included:

using System;
using Vorcyc.Mathematics.Calculus.NumericalMethods;

public class NewtonRaphsonExample
{
    public static void Main()
    {
        // Define the function
        var newtonRaphson = new NewtonRaphson<double>(x => x * x - 2.0, 1e-5);

        // Solve the equation
        double result = newtonRaphson.Solve(1.0);

        // Output result
        Console.WriteLine($"Newton-Raphson Test: Result = {result}");
    }
}

Vorcyc.Mathematics.Calculus.NumericalMethods.Bisection Class

Bisection<T> finds a root of f(x)=0 on the interval [a,b] using the bisection method; endpoint function values must have opposite signs.

  • public T Solve(T a, T b, int maxIterations = 100, T? tolerance = null)

Vorcyc.Mathematics.Calculus.NumericalMethods.Brent Class

Brent<T> robustly finds a root on the interval [a,b] using Brent's method, combining the stability of bisection with the speed of secant and inverse quadratic interpolation.

  • public T Solve(T a, T b, int maxIterations = 100, T? tolerance = null)

Vorcyc.Mathematics.Calculus.Hessian Class

Hessian<T> computes the Hessian matrix of a scalar multivariate function f: Rⁿ→R.

  • public Matrix<T> Calculate(Span<T> point, T? h = null)

Vorcyc.Mathematics.Calculus.NumericalMethods.AdaptiveRungeKutta Class

AdaptiveRungeKutta<T> adaptively solves dy/dx = f(x,y) using RK4 with step halving for error estimation.

  • public T Solve(T x0, T y0, T xEnd, T relativeTolerance, T absoluteTolerance, T? initialStep = null)

Vorcyc.Mathematics.Calculus.Series.FourierSeriesFromSamples Class

Estimates Fourier coefficients aₙ and bₙ from uniformly sampled periodic data (length must be a power of 2) via FFT, and reconstructs the series.

  • GetCosineCoefficient(int n) / GetSineCoefficient(int n) / Evaluate(float x, int order)

Vorcyc.Mathematics.Calculus.NumericalMethods.NewtonRaphsonSystem Class

NewtonRaphsonSystem<T> solves nonlinear systems F(x)=0 using a numerical Jacobian matrix and Gaussian elimination.

  • public T[] Solve(T[] initialGuess, int maxIterations = 50, T? tolerance = null)

Vorcyc.Mathematics.Calculus.NumericalMethods.AdaptiveRungeKuttaSystem Class

AdaptiveRungeKuttaSystem<T> adaptively integrates systems dy/dx = f(x,y) using RK4 with step halving.

  • public T[] Solve(T x0, ReadOnlySpan<T> y0, T xEnd, T relativeTolerance, T absoluteTolerance, T? initialStep = null)

Integration and Differentiation Precision Notes

  • Integration.Method.AdaptiveSimpson: n is the maximum recursion depth; h (or the constructor default step size) is the interval error tolerance.
  • Integration.Method.GaussLegendre: n must be 4, 8, or 16.
  • When h is null, Derivative selects step size h ≈ ε^(1/(n+2))·max(|x|,1) based on machine epsilon ε; first- and second-order central differences use Richardson extrapolation by default.

Optimization (Vorcyc.Mathematics.Calculus.Optimization)

  • BfgsOptimizer<T>.Minimize — Unconstrained minimization (dense inverse Hessian approximation)
  • LBfgsOptimizer<T>.Minimize — Limited-memory BFGS (default history length 10; suitable for high dimensions)
  • LevenbergMarquardt<T>.Solve — Nonlinear least squares
  • LineSearch.ArmijoBacktracking — Armijo backtracking line search

Performance Notes (Implementation Highlights)

Without changing public API semantics, the module reduces allocations and function evaluations through instance buffer reuse, SIMD vector kernels, and algorithm-level cost reduction (shared sampling, Horner/Clenshaw, Aitken acceleration, and more). double / float use SIMD paths in CalculusVectorOps.

Subsystem Main techniques
Vector kernels Dot, MatVec, JᵀJ, Jᵀr, ScaledMaxError, SymmetricBfgsUpdate, Rk4Accumulate, AddScaled, etc.
Optimizers BFGS/L-BFGS reuse gradients and search directions; LineSearch.ArmijoBacktracking(..., trial); stop via Dot(g,g)
Systems / LM Gaussian elimination workspace; separate trial/current residual buffers; Dot cost function
ODE SolveInPlace; RK k1–k4 reuse; OdeStepControl.GrowStep; shooting _perturbed buffer
Integration Romberg/adaptive Simpson stacks; Gauss node T[] tables; indefinite integration accumulation tables; improper integrals without closures
Differentiation Gradient(destination); Richardson shared stencils; OptimalMagnitude unified step size
Series Fourier presampling; Chebyshev cos(kθ) tables; Taylor coefficient arrays; FFT harmonic cache

Local benchmarks: benchmarks/basic_benchmark/Calculus_benchmark.cs (dotnet run -c Release --project benchmarks/basic_benchmark).

Performance Tuning Guide

General principles

  1. Reuse instances: Construct solvers, integrators, Derivative, Jacobian, FourierSeries, TaylorSeries, etc. outside loops; call repeatedly inside loops.
  2. Write into existing buffers: Prefer Gradient(point, destination), Jacobian/Hessian.Calculate(..., matrix?), LineSearch.ArmijoBacktracking(..., trial).
  3. In-place APIs: RungeKuttaSystem.SolveInPlace, Gaussian elimination GaussianEliminationSolve(..., workspace).
  4. Dedicated workspaces: Pass PadeWorkspace<T>, ChebyshevFitWorkspace<T> for repeated fitting.
  5. When to call ClearCache(): Only after the underlying function, step-size strategy, or bound parameters change; most optimizers/series objects do not need clearing every step.

By scenario

Scenario Recommendations
Repeated Fourier coefficients for the same function Reuse a FourierSeries instance; call ClearCache() only after the function or period changes
High-dimensional gradient / Jacobian Derivative.Gradient(point, destination); Jacobian.Calculate(..., matrix?); when h == null, step size is estimated automatically from max|x_i|
High-dimensional Hessian Hessian.Calculate(..., matrix?); symmetry is exploited—do not recompute the lower triangle
Batch ODE or shooting RungeKuttaSystem.SolveInPlace; ShootingBvpSolver reuses internal RK buffers
Adaptive ODE systems Reuse AdaptiveRungeKuttaSystem instances; double/float error estimation uses SIMD
Nonlinear systems / least squares Reuse NewtonRaphsonSystem / LevenbergMarquardt; use separate residual buffers for line search
BFGS / L-BFGS Reuse optimizer instances; LBfgsOptimizer for dimensions > tens; BfgsOptimizer for small to medium dimensions
Padé / Chebyshev fitting PadeWorkspace<T>, ChebyshevFitWorkspace<T> (includes cos(kθ) table)
Definite/indefinite integration with bound integrand After Integration(func, h), call Integrate without func; GetIndefiniteIntegral trapezoidal path auto-accumulates and builds tables
Double / Gauss integration Reuse the same Integration instance; nodes 4/8/16 are cached automatically
Taylor / Chebyshev evaluation Reuse TaylorSeries / ChebyshevSeries; coefficients cached on demand
Fourier from periodic samples FourierSeriesFromSamples; coefficients cached on demand up to order before Evaluate
Scalar root finding Reuse Brent / NewtonRaphson / Bisection instances

Second-Order Automatic Differentiation

  • HyperDualNumber<T> — Hyper-dual numbers; Derivative.SecondDerivativeAD; Hessian.CalculateAD
  • Hessian.Calculate(point, h, matrix?) — Optionally reuse the result matrix (same as Jacobian.Calculate)

ODE Trajectories and Boundary Values

  • RungeKutta.SolveTrajectory / RungeKuttaSystem.SolveTrajectory — Record trajectories and stop on events
  • AdaptiveRungeKutta.SolveTrajectory / AdaptiveRungeKuttaSystem.SolveTrajectory — Adaptive-step trajectories
  • ImplicitEuler — Stiff scalar ODE
  • ShootingBvpSolver — Shooting method for boundary-value problems (reuses RK state buffers; RungeKuttaSystem.SolveInPlace)

Series Extensions

  • PadeApproximant<T> — Padé rational approximation (optional PadeWorkspace<T> to reuse solve buffers)
  • ChebyshevSeries<T> — Chebyshev series fitting and evaluation (FromFunction samples each point once; optional ChebyshevFitWorkspace<T>)

Integration Extensions

  • Integration.IntegrateToInfinity — Improper integrals (truncation + tail correction)
  • Integration.IntegrateDouble — Double Gauss integration over a rectangular region

Language / 语言: English · 简体中文


Home


首页

Clone this wiki locally