Repository navigation
Module_Calculus
Location: Home / 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.Integration Class
- 🔖 Vorcyc.Mathematics.Calculus.Derivative Class
- 🔖 Vorcyc.Mathematics.Calculus.DualNumber Struct
- 🔖 Vorcyc.Mathematics.Calculus.Jacobian Class
- 🔖 Vorcyc.Mathematics.Calculus.Series.TaylorSeries Class
- 🔖 Vorcyc.Mathematics.Calculus.Series.FourierSeries Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.RungeKutta Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.RungeKuttaSystem Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.NewtonRaphson Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.Bisection Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.Brent Class
- 🔖 Vorcyc.Mathematics.Calculus.Hessian Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.AdaptiveRungeKutta Class
- 🔖 Vorcyc.Mathematics.Calculus.Series.FourierSeriesFromSamples Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.NewtonRaphsonSystem Class
- 🔖 Vorcyc.Mathematics.Calculus.NumericalMethods.AdaptiveRungeKuttaSystem 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.
-
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.
-
-
public void ClearCache()- Clears the function value cache for this instance.
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 is a class that provides numerical integration, supporting generic floating-point types.
-
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.
-
public T Integrate(T a, T b, int n, SingleVariableFunction<T> func, T? h = null, Method method = Method.Trapezoidal)- Computes the definite integral from
atob.
- Computes the definite integral from
-
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; supportsTrapezoidal,Simpson,Romberg,GaussLegendre,AdaptiveSimpson.
-
- Returns: Definite integral value.
- Exceptions:
-
ArgumentNullException: Thrown whenfuncis null. -
ArgumentException: Thrown whennis less than 1,his too small, or the method is not supported.
-
-
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.
-
public void ClearCache()- Clears the function value cache for this instance.
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 is a class that computes derivatives and partial derivatives, supporting both numerical methods and automatic differentiation.
-
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 whenorderis less than 1 or the step size is too small.
-
-
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.
-
-
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.
-
public void ClearCache()- Clears the cache for this instance.
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}");
}
}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); // eJacobian<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 is a class that provides Taylor series expansion computation, supporting generic floating-point types.
-
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 whenorderis less than 0.
-
-
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.
-
public void ClearCache()- Clears the derivative cache.
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 is a class that provides Fourier series expansion computation, supporting generic floating-point types.
-
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 whenorderis less than 0 orsegmentsis less than 1.
-
-
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 whennis less than 0 orsegmentsis less than 1. -
InvalidOperationException: Thrown when the integration result is invalid.
-
-
public void ClearCache()- Clears the function value cache for this instance.
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 is a class that solves ordinary differential equations using the Runge–Kutta method (RK4), supporting generic floating-point types.
-
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 whenstepsis less than 1.
-
-
public void ClearCache()- Clears the function value cache.
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}");
}
}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 is a class that solves nonlinear equations f(x) = 0 using the Newton–Raphson method, supporting generic floating-point types.
-
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 whenmaxIterationsis less than 1. -
InvalidOperationException: Thrown when the derivative is 0 or iteration fails to converge.
-
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}");
}
}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)
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)
Hessian<T> computes the Hessian matrix of a scalar multivariate function f: Rⁿ→R.
public Matrix<T> Calculate(Span<T> point, T? h = null)
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)
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)
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)
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.Method.AdaptiveSimpson:nis the maximum recursion depth;h(or the constructor default step size) is the interval error tolerance. -
Integration.Method.GaussLegendre:nmust be 4, 8, or 16. - When
his null,Derivativeselects step size h ≈ ε^(1/(n+2))·max(|x|,1) based on machine epsilon ε; first- and second-order central differences use Richardson extrapolation by default.
-
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
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).
General principles
-
Reuse instances: Construct solvers, integrators,
Derivative,Jacobian,FourierSeries,TaylorSeries, etc. outside loops; call repeatedly inside loops. -
Write into existing buffers: Prefer
Gradient(point, destination),Jacobian/Hessian.Calculate(..., matrix?),LineSearch.ArmijoBacktracking(..., trial). -
In-place APIs:
RungeKuttaSystem.SolveInPlace, Gaussian eliminationGaussianEliminationSolve(..., workspace). -
Dedicated workspaces: Pass
PadeWorkspace<T>,ChebyshevFitWorkspace<T>for repeated fitting. -
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 |
-
HyperDualNumber<T>— Hyper-dual numbers;Derivative.SecondDerivativeAD;Hessian.CalculateAD -
Hessian.Calculate(point, h, matrix?)— Optionally reuse the result matrix (same asJacobian.Calculate)
-
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)
-
PadeApproximant<T>— Padé rational approximation (optionalPadeWorkspace<T>to reuse solve buffers) -
ChebyshevSeries<T>— Chebyshev series fitting and evaluation (FromFunctionsamples each point once; optionalChebyshevFitWorkspace<T>)
-
Integration.IntegrateToInfinity— Improper integrals (truncation + tail correction) -
Integration.IntegrateDouble— Double Gauss integration over a rectangular region
-
- 🔖 ArrayExtension class
- 🔖 BaseConverter class
- 🔖 BitMathExtension class
- 🔖 Combinatorics class
- 🔖 ConstantsFp32 class
- 🔖 NumberMapper class
- 🔖 PinnableArray<T> class
- 🔖 SimpleRNG_Fp32 and SimpleRNG_Fp64 classes
- 🔖 TrigonometryHelper class
- 🔖 VMath class
- 🔖 Pinned buffers (Buffers)
- 🔖 IPinnedBuffer<T> interface
- 🔖 POHBuffer<T> class
- 🔖 NativeBuffer<T> class
-
- 🔖 0.9 classifier walkthrough
- 🔖 KNN<T> class
- 🔖 MultipleLinearRegression<T> class
- 🔖 SimpleLinearRegression<T> class
- 🔖 SupportVectorMachine<TSelf> class
- 🔖 DBSCAN<T> class
- 🔖 ExpectationMaximization<T> class
- 🔖 GMM<T> class
- 🔖 HierarchicalClustering<T> class
- 🔖 KMeansClusterer<T> class
- 🔖 VectorQuantization<T> class
- 🔖 FactorAnalysis<T> class
- 🔖 PCA<TSelf> class
- 🔖 TSNE<T> class
- 🔖 Distance metric classes
-
📒 Examples
-
📒 GPU 策略说明
- 🔖 为何放弃主包 GPU
- 🔖 当前性能路径
- 🔖 若仍需要更强算力
-
📒 计算上下文模块
-
📒 核心模块
-
📒 深度学习模块
-
📒 线性代数模块
-
📒 机器学习模块
- 🔖 0.9 分类器完整示例
- 🔖 KNN<T> 类
- 🔖 MultipleLinearRegression<T> 类
- 🔖 SimpleLinearRegression<T> 类
- 🔖 SupportVectorMachine<TSelf> 类
- 🔖 DBSCAN<T> 类
- 🔖 ExpectationMaximization<T> 类
- 🔖 GMM<T> 类
- 🔖 HierarchicalClustering<T> 类
- 🔖 KMeansClusterer<T> 类
- 🔖 VectorQuantization<T> 类
- 🔖 FactorAnalysis<T> 类
- 🔖 PCA<TSelf> 类
- 🔖 TSNE<T> 类
- 🔖 距离度量类
-
📒 信号处理模块
-
📒 数值模块
-
📒 统计模块
- 🔖 基础统计函数
- 🔖 高级统计函数
- 🔖 稳健统计 / RunningMoments
- 🔖 其它统计函数
- 🔖 分布相关函数
- 🔖 时间序列分析
- 🔖 IComparable 扩展
- 🔖 ExtremeValueFinder
- 🔖 INumber 扩展
-
📒 FFTW 扩展
-
📒 示例