sign_simd

Function sign_simd 

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

Compute the sign (signum) of each element (SIMD-accelerated).

Returns +1.0 for positive values, -1.0 for negative values, and 0.0 for zero.

§Arguments

  • x - Input 1D array

§Returns

Array1<F> with the same length as input, where each element is the sign of the input.

§Performance

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

§Mathematical Definition

sign(x) = { +1.0  if x > 0
          {  0.0  if x = 0
          { -1.0  if x < 0

§Properties

  • sign(-x) = -sign(x) (odd function)
  • sign(0) = 0
  • sign(x) * |x| = x
  • sign(x) * sign(y) = sign(x * y)
  • |sign(x)| ≤ 1 for all x

§Applications

  • Numerical Analysis: Gradient descent direction, optimization algorithms
  • Signal Processing: Phase detection, zero-crossing analysis
  • Physics Simulations: Force direction, velocity direction
  • Machine Learning: Feature engineering, binary classification features
  • Control Systems: Error sign for PID controllers
  • Game Development: Direction vectors, collision normals
  • Statistics: Wilcoxon signed-rank test, sign test
  • Finance: Market trend indicators (bull/bear)
  • Geometry: Surface normal orientation, vector direction
  • Image Processing: Edge direction, gradient orientation

§Examples

use scirs2_core::ndarray::array;
use scirs2_core::ndarray_ext::elementwise::sign_simd;

let x = array![-3.0_f64, -1.5, 0.0, 1.5, 3.0];
let result = sign_simd(&x.view());
assert_eq!(result[0], -1.0_f64); // negative → -1
assert_eq!(result[1], -1.0_f64); // negative → -1
assert_eq!(result[2],  0.0_f64); // zero → 0
assert_eq!(result[3],  1.0_f64); // positive → +1
assert_eq!(result[4],  1.0_f64); // positive → +1

// Property: sign(x) * |x| = x
let values = array![-5.0_f64, -2.0, 0.0, 2.0, 5.0];
let signs = sign_simd(&values.view());
let abs_values = values.mapv(|x: f64| x.abs());
let reconstructed = signs * abs_values;
for i in 0..values.len() {
    assert!((reconstructed[i] - values[i]).abs() < 1e-10);
}

§See Also

  • abs_simd: Magnitude without sign
  • clamp_simd: Constrain values to a range