clip_simd

Function clip_simd 

Source
pub fn clip_simd<F>(x: &ArrayView1<'_, F>, min_val: F, max_val: F) -> Array1<F>
where F: Float + SimdUnifiedOps,
Expand description

Clip (clamp) array values to a specified range (SIMD-accelerated).

Constrains each element to be within [min_val, max_val]:

  • Values < min_val are set to min_val
  • Values > max_val are set to max_val
  • Values within range are unchanged

§Arguments

  • x - Input 1D array to clip
  • min_val - Minimum allowed value
  • max_val - Maximum allowed value

§Returns

Array1<F> with the same length as input, with values clipped to [min_val, max_val].

§Panics

Panics if min_val > max_val.

§Performance

  • SIMD: Automatically used for large arrays (1000+ elements)
  • Scalar: Used for small arrays or when SIMD unavailable
  • Speedup: 2-4x for large f32 arrays on AVX2 systems

§Mathematical Definition

clip(x, min, max) = {
    min     if x < min
    max     if x > max
    x       otherwise
}

§Examples

use scirs2_core::ndarray::array;
use scirs2_core::ndarray_ext::preprocessing::clip_simd;

let x = array![-10.0, -5.0, 0.0, 5.0, 10.0];
let result = clip_simd(&x.view(), -3.0, 7.0);

// Values clipped to [-3.0, 7.0]
assert_eq!(result[0], -3.0);  // -10 -> -3
assert_eq!(result[1], -3.0);  // -5 -> -3
assert_eq!(result[2], 0.0);   // 0 unchanged
assert_eq!(result[3], 5.0);   // 5 unchanged
assert_eq!(result[4], 7.0);   // 10 -> 7

§Edge Cases

  • Empty array: Returns empty array
  • min_val == max_val: All values set to that value
  • NaN values: Behavior is platform-dependent (typically become min_val)
  • Infinite values: Clipped to min/max as appropriate

§Applications

  • Gradient Clipping: Prevent exploding gradients in neural network training
  • Outlier Handling: Remove or bound extreme values in statistical analysis
  • Data Preprocessing: Enforce valid ranges for features
  • Numerical Stability: Prevent overflow/underflow in computations
  • Image Processing: Clamp pixel values to valid ranges
  • Audio Processing: Prevent clipping distortion

§Example: Gradient Clipping

use scirs2_core::ndarray::array;
use scirs2_core::ndarray_ext::preprocessing::clip_simd;

// Clip gradients to prevent exploding gradients
let gradients = array![10.5, -8.2, 0.3, 15.7, -12.1];
let clipped = clip_simd(&gradients.view(), -5.0, 5.0);

// All gradients now in [-5.0, 5.0]
assert_eq!(clipped[0], 5.0);   // 10.5 -> 5.0
assert_eq!(clipped[1], -5.0);  // -8.2 -> -5.0
assert_eq!(clipped[2], 0.3);   // unchanged
assert_eq!(clipped[3], 5.0);   // 15.7 -> 5.0
assert_eq!(clipped[4], -5.0);  // -12.1 -> -5.0