Skip to content

XMath - Utility Functions for Mathematical Operations

Path: 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.

  • C++17 compiler support
  • No hardware-specific requirements
  • clamp<T>() - 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]
  • 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
  • None

Application

XMath

The XMath utilities provide deterministic mathematical operations:

value < low

value > high

low ≤ value ≤ high

min < value < max

else

Input Value

clamp

Return low

Return high

Return value

Input Value

RANGE

Return true

Return false

Input Value

NCLAMP

Normalize to 0.0-1.0 range

  • Consider specialized implementations for common numeric types to avoid template instantiation overhead
  • Evaluate potential for SIMD optimizations on compatible platforms
  • No known security concerns as the utilities perform pure mathematical operations without side effects
  • Ensure all mathematical operations maintain expected precision for safety-critical applications
  • Verify behavior with edge cases (e.g., handling of NaN, Inf values)
  • Use clamp<T>() 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