--- title: "XMath - Utility Functions for Mathematical Operations" description: "Lightweight mathematical functions including template-based clamping and range checking" keywords: ["ESP-32", "math", "clamp", "range", "normalize"] --- ## XMath **Path**: [`src/modbus/xmath.h`](../src/modbus/xmath.h) **Revision History**: - Initial documentation A lightweight utility header that provides essential mathematical operations for embedded systems. It includes a template-based clamp function and macros for range checking and normalized clamping. ## REQUIREMENTS - C++17 compiler support - No hardware-specific requirements ## PROVIDES - `clamp()` - Template function for clamping values within specified bounds - `RANGE()` - Macro for checking if a value is within a specified range - `NCLAMP()` - Macro for normalizing a value within a range to [0.0, 1.0] ## FEATURES - Type-generic clamping through template implementation - Range checking for value validation - Value normalization to a [0.0, 1.0] range - Conditional compilation for C++ environments - No standard library dependencies ## DEPENDENCIES - None ```mermaid graph TD Application --> XMath ``` ## BEHAVIOUR The XMath utilities provide deterministic mathematical operations: ```mermaid graph LR A[Input Value] --> B{clamp} B --> |value < low| C[Return low] B --> |value > high| D[Return high] B --> |low ≤ value ≤ high| E[Return value] F[Input Value] --> G{RANGE} G --> |min < value < max| H[Return true] G --> |else| I[Return false] J[Input Value] --> K{NCLAMP} K --> L[Normalize to 0.0-1.0 range] ``` ## TODOS ### PERFORMANCE - Consider specialized implementations for common numeric types to avoid template instantiation overhead - Evaluate potential for SIMD optimizations on compatible platforms ### SECURITY - No known security concerns as the utilities perform pure mathematical operations without side effects ### COMPLIANCE - Ensure all mathematical operations maintain expected precision for safety-critical applications - Verify behavior with edge cases (e.g., handling of NaN, Inf values) ### RECOMMENDATIONS - Use `clamp()` when working with specific types to leverage compile-time type checking - Prefer the NCLAMP macro when normalizing sensor readings or other input values to a standardized range - Consider adding additional mathematical utilities as needed for specific application domains