Math Module
rmath.calculus
Automatic differentiation via dual numbers, numerical integration (trapezoidal and Simpson's rule), and Newton's method for root-finding.
autodiff.py
import rmath.calculus as rc
# f(x) = x² + 3x at x = 2
x = rc.Dual(2.0, 1.0) # value=2, seed derivative=1
y = x * x + x * 3.0
print(y.value) # 10.0
print(y.derivative) # 7.0 → f'(2) = 2(2) + 3
Dual Numbers
Dual numbers a + bε (where ε² = 0) enable forward-mode automatic differentiation. Build an expression using Dual operands and the derivative is computed alongside the value.
Constructor & Properties
Dual(val, der) | Create a dual number with value and derivative seed | |
.value | float | The real part |
.derivative | float | The derivative (epsilon coefficient) |
Operators
+ - * / ** | All work with Dual or float operands, propagating derivatives automatically |
-x | Unary negation |
Math Functions
.sin() | sin(x), derivative: cos(x) |
.cos() | cos(x), derivative: -sin(x) |
.exp() | eˣ, derivative: eˣ |
.log() | ln(x), derivative: 1/x |
Numerical Integration
| Function | Description |
|---|---|
integrate_trapezoidal(x, y) | Trapezoidal rule on sampled data (x, y vectors) |
integrate_simpson_array(y, dx) | Simpson's rule on uniformly-spaced samples |
integrate_simpson(f, a, b, n) | Simpson's rule on a callable f over [a, b] with n intervals |
Root-Finding
| Function | Description |
|---|---|
find_root_newton(f, x0, tol, max_iter) | Newton's method using autodiff. f takes a Dual and returns a Dual. Derivatives are computed automatically. |
root.py
import rmath.calculus as rc
# Find root of f(x) = x² - 2 → x = √2
def f(x):
return x * x - 2.0
root = rc.find_root_newton(f, x0=1.0, tol=1e-12, max_iter=50)
# root ≈ 1.4142135623730951