From 04bf7673f350bb1bccf8a875cc25c13a9b963650 Mon Sep 17 00:00:00 2001 From: Jacob Lifshay Date: Wed, 12 May 2021 19:08:32 -0700 Subject: [PATCH] add abs_f16/32/64 --- src/algorithms.rs | 1 + src/algorithms/base.rs | 56 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/algorithms/base.rs diff --git a/src/algorithms.rs b/src/algorithms.rs index 76907f4..cfa78b8 100644 --- a/src/algorithms.rs +++ b/src/algorithms.rs @@ -1,2 +1,3 @@ +pub mod base; pub mod ilogb; pub mod trig_pi; diff --git a/src/algorithms/base.rs b/src/algorithms/base.rs new file mode 100644 index 0000000..56691a3 --- /dev/null +++ b/src/algorithms/base.rs @@ -0,0 +1,56 @@ +use crate::traits::{Context, Float}; + +pub fn abs_f16(ctx: Ctx, x: Ctx::VecF16) -> Ctx::VecF16 { + Ctx::VecF16::from_bits(x.to_bits() & ctx.make(0x7FFFu16)) +} + +pub fn abs_f32(ctx: Ctx, x: Ctx::VecF32) -> Ctx::VecF32 { + Ctx::VecF32::from_bits(x.to_bits() & ctx.make(!(1u32 << 31))) +} + +pub fn abs_f64(ctx: Ctx, x: Ctx::VecF64) -> Ctx::VecF64 { + Ctx::VecF64::from_bits(x.to_bits() & ctx.make(!(1u64 << 63))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + f16::F16, + scalar::{Scalar, Value}, + }; + + #[test] + #[cfg_attr( + not(feature = "f16"), + should_panic(expected = "f16 feature is not enabled") + )] + fn test_abs_f16() { + for bits in 0..=u16::MAX { + let v = F16::from_bits(bits); + let expected = v.abs(); + let result = abs_f16(Scalar, Value(v)).0; + assert_eq!(expected.to_bits(), result.to_bits()); + } + } + + #[test] + fn test_abs_f32() { + for bits in (0..=u32::MAX).step_by(10001) { + let v = f32::from_bits(bits); + let expected = v.abs(); + let result = abs_f32(Scalar, Value(v)).0; + assert_eq!(expected.to_bits(), result.to_bits()); + } + } + + #[test] + fn test_abs_f64() { + for bits in (0..=u64::MAX).step_by(100_000_000_000_001) { + let v = f64::from_bits(bits); + let expected = v.abs(); + let result = abs_f64(Scalar, Value(v)).0; + assert_eq!(expected.to_bits(), result.to_bits()); + } + } +} -- 2.30.2