
Math Review
- 106 installs
- 325 repo stars
- Updated August 2, 2026
- athola/claude-night-market
Install math-review when your agent or backend relies on derivations, approximations, or probabilistic formulas and you need a structured pass before you trust the numbers.
About
math-review is an agent skill for solo builders who ship code where the math must be right—not merely plausible. It walks you through derivation verification: re-derive critical formulas symbolically, compare implementations to notebook checks (for example SymPy gradients), and validate probabilistic steps before they drive product logic. It then challenges approximations you often skip in a hurry: series truncation order and error, linearization validity, surrogate models against ground truth, and documented bounds tested at edges of the domain. The tone fits indie ML, simulation, pricing, and scientific backends where a wrong gradient or Bayes step is expensive. Use it during prototype review, while documenting model assumptions, or as a structured pre-ship review when formulas and numerics underpin your feature. It does not replace a full formal V&V program, but it gives your coding agent a repeatable checklist aligned with recognized modeling standards.
- Symbolic verification workflow using SymPy, Mathematica, or Maple against handwritten algebra and calculus
- Probabilistic reasoning checks: conditional probability, Bayes rule, expectations, variances, and distribution propertie
- Approximation audit: series truncation order, linearization domains, surrogate vs ground-truth comparison
- Error-bound derivation with empirical checks at domain boundaries and worst-case scenarios
- Grounded in NASA-STD-7009 and ASME V&V 20 modeling and simulation verification expectations
Math Review by the numbers
- 106 all-time installs (skills.sh)
- Ranked #817 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/athola/claude-night-market --skill math-reviewAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 106 |
|---|---|
| repo stars | ★ 325 |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | athola/claude-night-market ↗ |
What it does
Install math-review when your agent or backend relies on derivations, approximations, or probabilistic formulas and you need a structured pass before you trust the numbers.
Files
Table of Contents
- Quick Start
- When to Use
- Required TodoWrite Items
- Core Workflow
- 1. Context Sync
- 2. Requirements Mapping
- 3. Derivation Verification
- 4. Stability Assessment
- 5. Proof of Work
- Progressive Loading
- Essential Checklist
- Output Format
- Summary
- Context
- Requirements Analysis
- Derivation Review
- Stability Analysis
- Issues
- Recommendation
- Exit Criteria
Mathematical Algorithm Review
Intensive analysis ensuring numerical stability and alignment with standards.
Quick Start
/math-reviewVerification: Run the command with --help flag to verify availability.
When To Use
- Changes to mathematical models or algorithms
- Statistical routines or probabilistic logic
- Numerical integration or optimization
- Scientific computing code
- ML/AI model implementations
- Safety-critical calculations
When NOT To Use
- General algorithm review -
use architecture-review
- Performance optimization - use parseltongue:python-performance
- General algorithm review -
use architecture-review
- Performance optimization - use parseltongue:python-performance
Required TodoWrite Items
1. math-review:context-synced 2. math-review:requirements-mapped 3. math-review:derivations-verified 4. math-review:stability-assessed 5. math-review:evidence-logged 6. math-review:findings-verified
Core Workflow
1. Context Sync
pwd && git status -sb && git diff --stat origin/main..HEADVerification: Run git status to confirm working tree state. Enumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.
2. Requirements Mapping
Translate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. Load: modules/requirements-mapping.md
3. Derivation Verification
Re-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). Load: modules/derivation-verification.md
4. Stability Assessment
Evaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. Load: modules/numerical-stability.md
5. Proof of Work
pytest tests/math/ --benchmark
jupyter nbconvert --execute derivation.ipynbVerification: Run pytest -v tests/math/ to verify. Log deviations, recommend: Approve / Approve with actions / Block. Load: modules/testing-strategies.md
6. Verify Findings Are Grounded (math-review:findings-verified)
Every issue must cite a real location and a verbatim anchor. Write findings to .review/findings.json and confirm each citation resolves:
python plugins/imbue/scripts/citation_verifier.py \
--findings .review/findings.json --repo-root .Drop or label UNVERIFIED any finding the verifier fails (exit 1); only verified findings enter the report. See Skill(imbue:review-core) Step 5 for the protocol and Skill(imbue:structured-output) for the finding schema.
Progressive Loading
Default (200 tokens): Core workflow, checklists +Requirements (+300 tokens): Invariants, pre/post conditions, coverage analysis +Derivation (+350 tokens): CAS verification, standards, citations +Stability (+400 tokens): Numerical properties, precision, complexity +Testing (+350 tokens): Edge cases, benchmarks, reproducibility
Total with all modules: ~1600 tokens
Essential Checklist
Correctness: Formulas match spec | Edge cases handled | Units consistent | Domain enforced Stability: Condition number OK | Precision sufficient | No cancellation | Overflow prevented Verification: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible Documentation: Assumptions stated | Limitations documented | Error bounds specified | References linked
Output Format
## Summary
[Brief findings]
## Context
Files | Risk classification | Standards
## Requirements Analysis
| Invariant | Verified | Evidence |
## Derivation Review
[Status and conflicts]
## Stability Analysis
Condition number | Precision | Risks
## Issues
[M1] [Title]
- Location: file.py:123
- Anchor: `verbatim source text at line 123`
- Issue: [what is wrong] | Fix: [remediation] | Evidence: [E1]
## Recommendation
Approve / Approve with actions / BlockEvery issue's Anchor is the exact source text at Location; it is what citation_verifier.py re-reads to prove the finding is real. Verification: Run the command with --help flag to verify availability.
Exit Criteria
- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations
- Every reported issue carries a
Location+ verbatimAnchor, andcitation_verifier.pyconfirmed all citations (exit0) or unverified issues were dropped or labeledUNVERIFIED
Derivation Verification
Re-derive Critical Formulas
Symbolic Verification
- Use Computer Algebra Systems (SymPy, Mathematica, Maple)
- Confirm algebraic manipulations
- Verify calculus operations (derivatives, integrals)
- Check limit behavior
Computational Notebooks
# Example: Verify gradient computation
import sympy as sp
x, y = sp.symbols('x y')
f = x**2 + y**2
grad_f = [sp.diff(f, var) for var in [x, y]]
# Compare with implementationProbabilistic Reasoning
- Verify conditional probability formulas
- Check Bayes rule applications
- Confirm expectation/variance calculations
- Validate distribution properties
Challenge Approximations
Series Truncation
- Document truncation order (e.g., O(h³))
- Estimate truncation error
- Test convergence with different orders
- Provide error bounds across domain
Linearizations
- Identify linearization points
- Estimate valid domain size
- Test against full nonlinear model
- Document approximation quality
Surrogate Models
- Compare surrogate to ground truth
- Quantify approximation error
- Document training/validation data
- Test extrapolation behavior
Error Bounds
- Derive theoretical error bounds
- Verify empirically
- Document worst-case scenarios
- Test at domain boundaries
Authoritative References
Standards and Frameworks
- NASA-STD-7009: Modeling and Simulation V&V
- ASME V&V 20: Verification & Validation in CFD/HT
- ASME V&V 10: Guide for V&V in Computational Solid Mechanics
- SIAM: Reproducibility checklists
- IEEE 754: Floating-point arithmetic
- NIST: Uncertainty quantification guidelines
Academic Sources
- Peer-reviewed papers (DOI links)
- Textbooks (edition and page numbers)
- Technical reports
- Conference proceedings
Implementation References
- Reference implementations (NumPy, SciPy, GSL)
- Algorithm papers (original sources)
- Numerical recipes
- Domain-specific libraries
Document Conflicts
When implementation deviates from standards:
### Deviation: [Brief title]
- **Standard**: NASA-STD-7009 Section 3.4.2
- **Requirement**: Monte Carlo with n≥1000 samples
- **Implementation**: n=100 samples
- **Justification**: Performance constraints
- **Risk**: Reduced confidence intervals
- **Mitigation**: Document uncertainty, flag results
- **Owner**: [name]
- **Due date**: [date]Citation Format
## References
[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.
Prentice-Hall. Chapter 3.
[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.
Section 4.2: Verification Requirements.
[3] Goldberg, D. (1991). "What Every Computer Scientist Should Know
About Floating-Point Arithmetic". *ACM Computing Surveys*, 23(1).
DOI: 10.1145/103162.103163Verification Checklist
- [ ] Formulas re-derived from first principles
- [ ] Symbolic verification completed (CAS)
- [ ] Approximation order documented
- [ ] Error bounds derived and tested
- [ ] Authoritative references cited
- [ ] Deviations from standards documented
- [ ] Conflicts resolved or flagged
- [ ] Implementation matches theory
Numerical Stability Analysis
Conditioning
Condition Numbers
- Measure sensitivity to input perturbations
- High condition number = unstable computation
- Use scaled condition numbers when possible
Sensitivity Analysis
- Perturb inputs systematically
- Measure output variation
- Document acceptable tolerance ranges
Precision Management
Floating-Point Error Propagation
# Bad: Accumulating small values into large
total = 1e15
for x in small_values:
total += x # Precision lost
# Good: Kahan summation or sort first
sorted_values = sorted(small_values)
total = sum(sorted_values) # Better precisionCatastrophic Cancellation
# Bad: Subtracting similar values
result = (a + epsilon) - a # Catastrophic cancellation
# Good: Reformulate to avoid
result = epsilon # Direct computationOverflow/Underflow Prevention
- Check dynamic range before operations
- Use log-space for very large/small products
- Normalize intermediate results
- Scale inputs to manageable ranges
Scaling and Normalization
Dynamic Range Handling
- Pre-scale inputs to [0, 1] or [-1, 1]
- Use log-transforms for exponential data
- Document scaling factors and units
Normalization Requirements
- L1/L2 normalization for vectors
- Feature scaling for ML inputs
- Unit conversions for physical quantities
Randomness Control
Reproducibility
- Set explicit random seeds
- Document PRNG algorithms used
- Version lock numerical libraries
- Test deterministic behavior
Seed Management
# Good: Explicit seed control
import numpy as np
np.random.seed(42)
# Better: Isolated RNG state
rng = np.random.RandomState(42)
samples = rng.normal(0, 1, size=100)Complexity Analysis
Compare algorithmic complexity before/after changes:
Before: O(n²) time, O(n) space
After: O(n log n) time, O(n) space
Improvement: 100x faster for n=1000Document:
- Time complexity
- Space complexity
- Cache behavior
- Parallelization potential
Uncertainty Quantification
Required for:
- Safety-critical systems
- Data-driven components
- High-stakes decisions
- Regulatory compliance
Methods:
- Monte Carlo sampling
- Bootstrap confidence intervals
- Sensitivity analysis
- Error propagation formulas
Stability Checklist
- [ ] Condition number < 1e6
- [ ] Precision loss < 1e-10
- [ ] No catastrophic cancellation
- [ ] Overflow/underflow prevented
- [ ] Scaling applied appropriately
- [ ] Random seeds controlled
- [ ] Complexity acceptable
- [ ] Uncertainty quantified (if required)
Requirements Mapping
Mathematical Invariants
Translate requirements into verifiable mathematical properties:
| Requirement | Invariant | Test Coverage |
|---|---|---|
| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |
| Conservation | Σ mass_in = Σ mass_out | Unit test |
| Bounded error | \ | ε\ |
| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |
| Idempotence | f(f(x)) = f(x) | Unit test |
Pre-conditions
Input Validation
def compute(x: float, n: int) -> float:
"""Compute function with documented preconditions.
Preconditions:
- x ≥ 0 (non-negative input)
- n > 0 (positive integer)
- x < 1e10 (prevent overflow)
"""
if x < 0:
raise ValueError("x must be non-negative")
if n <= 0:
raise ValueError("n must be positive")
if x >= 1e10:
raise ValueError("x must be < 1e10")
# ... implementationDomain Constraints
- Valid input ranges
- Type requirements
- Dimensional consistency
- Unit compatibility
Post-conditions
Output Guarantees
def normalize(vector: np.ndarray) -> np.ndarray:
"""Normalize vector to unit length.
Postconditions:
- ||result|| = 1.0 (± 1e-10)
- result ∥ vector (parallel)
"""
result = vector / np.linalg.norm(vector)
assert abs(np.linalg.norm(result) - 1.0) < 1e-10
return resultInvariant Preservation
- Conservation laws maintained
- Bounds respected
- Relationships preserved
Conservation Laws
Physical Conservation
- Mass conservation
- Energy conservation
- Momentum conservation
- Charge conservation
Numerical Conservation
- Probability sums to 1.0
- Symmetry preservation
- Balance equations
Monotonicity Guarantees
Increasing Functions
# Property test
@given(st.floats(min_value=0, max_value=100))
def test_monotonic_increasing(x1, x2):
assume(x1 < x2)
assert f(x1) <= f(x2)Convexity/Concavity
- Second derivative tests
- Jensen's inequality
- Midpoint properties
Probabilistic Bounds
Confidence Intervals
- Document confidence levels (95%, 99%)
- Specify interval type (credible, confidence)
- Test coverage probabilities
Error Probabilities
- Type I/II error rates
- False positive/negative rates
- Statistical power
Coverage Gap Analysis
Identify untested invariants:
### Coverage Gaps
**Missing Tests**
- [ ] Boundary condition: x = 0
- [ ] Overflow case: x > 1e15
- [ ] Negative input handling
- [ ] Conservation at t → ∞
**Insufficient Coverage**
- [ ] Only 3 test cases for n-dimensional invariant
- [ ] No property tests for monotonicity
- [ ] Missing edge case: empty inputDocumentation Template
def algorithm(inputs) -> outputs:
"""Brief description.
Mathematical Properties:
- Preconditions: [domain constraints]
- Postconditions: [guaranteed properties]
- Invariants: [preserved relationships]
- Complexity: [time/space bounds]
- Stability: [condition number, error bounds]
References:
- [Citation to algorithm source]
"""Mapping Checklist
- [ ] Requirements translated to invariants
- [ ] Pre-conditions documented
- [ ] Post-conditions verified
- [ ] Conservation laws tested
- [ ] Monotonicity/convexity checked
- [ ] Probabilistic bounds specified
- [ ] Coverage gaps identified
- [ ] All properties have tests
Testing Strategies for Mathematical Code
Edge Case Coverage
Domain Boundaries
# Bad: Undefined for negative
result = math.sqrt(value)
# Good: Validate domain
def safe_sqrt(value: float) -> float:
if value < 0:
raise ValueError("sqrt requires non-negative input")
return math.sqrt(value)
# Test edge cases
@pytest.mark.parametrize("value", [0, 1e-100, 1e100, float('inf')])
def test_sqrt_boundaries(value):
result = safe_sqrt(value)
assert result >= 0Special Values
- Zero
- One
- Infinity
- NaN
- Very small (underflow)
- Very large (overflow)
- Negative values
- Empty inputs
Property-Based Testing
Hypothesis Framework
from hypothesis import given, strategies as st
@given(st.floats(min_value=0, max_value=1e6))
def test_sqrt_inverse(x):
"""sqrt(x)² should equal x"""
result = safe_sqrt(x)
assert abs(result * result - x) < 1e-10 * xInvariant Testing
- Symmetry properties
- Associativity/commutativity
- Idempotence
- Conservation laws
- Monotonicity
Benchmark Testing
Performance Validation
pytest tests/math/ --benchmark-only
pytest tests/math/ --benchmark-compare=baselineRegression Detection
def test_algorithm_performance(benchmark):
"""validate O(n log n) complexity maintained"""
n = 10000
data = np.random.rand(n)
result = benchmark(algorithm, data)
# Verify result correctness
assert len(result) == n
# Performance constraint
assert benchmark.stats['mean'] < 0.1 # secondsComplexity Verification
- Time scaling tests
- Memory profiling
- Cache behavior
- Parallel efficiency
Reproducibility Testing
Deterministic Results
def test_reproducibility():
"""Same seed produces same results"""
np.random.seed(42)
result1 = monte_carlo_simulation()
np.random.seed(42)
result2 = monte_carlo_simulation()
np.testing.assert_array_equal(result1, result2)Version Pinning
# pyproject.toml
[tool.poetry.dependencies]
numpy = "==1.24.0" # Pin for reproducibility
scipy = "==1.10.0"Reference Implementation Tests
Golden Master Testing
def test_against_reference():
"""Compare with NumPy/SciPy reference"""
x = np.linspace(0, 10, 100)
our_result = our_implementation(x)
reference_result = scipy.special.reference_function(x)
np.testing.assert_allclose(
our_result,
reference_result,
rtol=1e-10,
atol=1e-12
)Cross-Validation
- Multiple independent implementations
- Different algorithms
- Analytical solutions (when available)
- Published test cases
Numerical Accuracy Tests
Tolerance Specifications
# Absolute tolerance
np.testing.assert_allclose(result, expected, atol=1e-10)
# Relative tolerance
np.testing.assert_allclose(result, expected, rtol=1e-8)
# Both
np.testing.assert_allclose(
result, expected,
rtol=1e-8, atol=1e-10
)ULP (Units in Last Place) Testing
# For critical floating-point comparisons
assert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))Evidence Logging
Execution Records
# Run tests with output capture
pytest tests/math/ -v --tb=short > test_results.txt
# Benchmark with JSON output
pytest tests/math/ --benchmark-json=benchmark.json
# Execute derivation notebooks
jupyter nbconvert --execute derivation.ipynb \
--to html --output verification.htmlDocumentation Template
## Test Evidence
### Unit Tests
- **Command**: `pytest tests/math/ -v`
- **Result**: 47/47 passed
- **Coverage**: 94%
- **Date**: 2025-12-06
### Benchmarks
- **Command**: `pytest tests/math/ --benchmark-only`
- **Mean time**: 23.4ms (±1.2ms)
- **Baseline**: 24.1ms
- **Improvement**: 3%
### Derivation Verification
- **Notebook**: derivation.ipynb
- **Status**: All cells executed successfully
- **Symbolic checks**: Passed
- **Reference comparison**: Within toleranceTest Organization
tests/math/
├── test_correctness.py # Basic functionality
├── test_edge_cases.py # Boundary conditions
├── test_properties.py # Hypothesis tests
├── test_benchmarks.py # Performance
├── test_stability.py # Numerical stability
├── test_references.py # Golden masters
└── fixtures/
├── test_data.npz
└── reference_results.jsonTesting Checklist
- [ ] Edge cases covered (0, ±∞, NaN)
- [ ] Property tests for invariants
- [ ] Benchmark tests for performance
- [ ] Reproducibility verified
- [ ] Reference implementation compared
- [ ] Tolerances documented
- [ ] Evidence logged and dated
- [ ] Coverage > 90% for math code
Related skills
FAQ
Is Math Review safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.