expression
Normalize a finite nonzero direction
Normalization changes a nonzero vector to a unit-length direction. Zero has no direction. The helper also rejects nonfinite inputs and nonfinite magnitudes; this conservative implementation may reject huge finite vectors whose magnitude overflows. A production library may use scaling to handle a broader range. Compare floating results with tolerances, not exact equality. Expected result (NOT RUN): 0.6, 0.8 zero rejected: true Common mistake: Dividing a zero vector by zero or ignoring nonfinite inputs. Static Rust example; not a verified ByteMind executable assessment.
Formal Syntax & Structure
rust syntaxrust
v / length; return None for invalid inputWorking Example
Example Snippetrust
fn unit(x: f64, y: f64) -> Option<[f64; 2]> { if !x.is_finite() || !y.is_finite() { return None; } let len = x.hypot(y); if len == 0.0 || !len.is_finite() { return None; } // Scale before division to handle very small nonzero magnitudes accurately. let scale = x.abs().max(y.abs()); let (a, b) = (x / scale, y / scale); let n = a.hypot(b); Some([a / n, b / n])}fn main() { let [x, y] = unit(3.0, 4.0).unwrap(); assert!((x.hypot(y) - 1.0).abs() < 1e-12); println!("{x:.1}, {y:.1}"); println!("zero rejected: {}", unit(0.0, 0.0).is_none());}