Skip to main content

elem_simd_math/
dispatch.rs

1//! Slice entry points: elementwise application over contiguous buffers.
2//!
3//! Every function writes `dst[i] = f(src[i])` for all `i`, using the best SIMD level the CPU
4//! supports at runtime. `dst` may be uninitialized storage: each element is written exactly once
5//! on success, so callers do not have to zero-fill a buffer that is fully overwritten.
6//!
7//! Without the (default) `simd` feature the implementations fall back to the platform's scalar
8//! transcendental functions. Functions with no scalar equivalent in the standard library
9//! (`erf`, `erfc`, `tgamma`, `lgamma`, `sinpi`, `cospi`, `sincospi`) are only available with
10//! `simd`; they would otherwise need a second scalar implementation of SLEEF to stay honest
11//! about their error bounds.
12
13use core::mem::MaybeUninit;
14
15/// The source and destination lengths differ.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct LengthMismatch {
18    /// Number of elements in the first input slice.
19    pub src: usize,
20    /// Number of elements in the destination slice.
21    pub dst: usize,
22}
23
24impl core::fmt::Display for LengthMismatch {
25    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26        write!(
27            f,
28            "input has {} elements but the destination has {}",
29            self.src, self.dst
30        )
31    }
32}
33
34impl std::error::Error for LengthMismatch {}
35
36/// Elementwise math over contiguous slices.
37///
38/// Implemented for `f64`. The accuracy tier and error bound of each function are
39/// documented on the kernels in [`crate::f64x`]; each method selects the most
40/// accurate tier available for that function. The tier-specific entry points are the `*_u35`
41/// free functions in [`crate::f64`].
42pub trait ElementwiseMath: Copy + 'static {
43    /// Natural exponential function; 1.0 ULP.
44    fn exp(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
45    /// Base-2 exponential function; 1.0 ULP.
46    fn exp2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
47    /// Base-10 exponential function; 1.09 ULP.
48    fn exp10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
49    /// Natural exponential function minus one; 1.0 ULP.
50    fn expm1(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
51    /// Natural logarithm; 1.0 ULP.
52    fn log(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
53    /// Base-2 logarithm; 1.0 ULP.
54    fn log2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
55    /// Base-10 logarithm; 1.0 ULP.
56    fn log10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
57    /// Logarithm of one plus the argument; 1.0 ULP.
58    fn log1p(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
59    /// Sine function; 1.0 ULP.
60    fn sin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
61    /// Cosine function; 1.0 ULP.
62    fn cos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
63    /// Tangent function; 1.0 ULP.
64    fn tan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
65    /// Arc sine function; 1.0 ULP.
66    fn asin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
67    /// Arc cosine function; 1.0 ULP.
68    fn acos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
69    /// Arc tangent function; 1.0 ULP.
70    fn atan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
71    /// Hyperbolic sine function; 1.0 ULP.
72    fn sinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
73    /// Hyperbolic cosine function; 1.0 ULP.
74    fn cosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
75    /// Hyperbolic tangent function; 1.0 ULP.
76    fn tanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
77    /// Inverse hyperbolic sine function; 1.0 ULP.
78    fn asinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
79    /// Inverse hyperbolic cosine function; 1.0 ULP.
80    fn acosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
81    /// Inverse hyperbolic tangent function; 1.0 ULP.
82    fn atanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
83    /// Cube root function; 1.0 ULP.
84    fn cbrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
85    /// Square root function; `0.5001 ULP`.
86    fn sqrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
87    /// Argument raised to an argument power; 1.0 ULP.
88    fn pow(lhs: &[Self], rhs: &[Self], dst: &mut [MaybeUninit<Self>])
89        -> Result<(), LengthMismatch>;
90    /// Arc tangent of two arguments; 1.0 ULP.
91    fn atan2(
92        lhs: &[Self],
93        rhs: &[Self],
94        dst: &mut [MaybeUninit<Self>],
95    ) -> Result<(), LengthMismatch>;
96    /// Euclidean distance in two dimensions; `0.5001 ULP`.
97    fn hypot(
98        lhs: &[Self],
99        rhs: &[Self],
100        dst: &mut [MaybeUninit<Self>],
101    ) -> Result<(), LengthMismatch>;
102    /// Sine and cosine together; 1.0 ULP.
103    fn sincos(
104        src: &[Self],
105        sin: &mut [MaybeUninit<Self>],
106        cos: &mut [MaybeUninit<Self>],
107    ) -> Result<(), LengthMismatch>;
108}
109
110/// Writes `f(src[i])` into every slot of `dst`.
111#[cfg_attr(feature = "simd", allow(dead_code))]
112pub(crate) fn scalar_apply<T: Copy>(src: &[T], dst: &mut [MaybeUninit<T>], f: impl Fn(T) -> T) {
113    for (slot, &value) in dst.iter_mut().zip(src.iter()) {
114        slot.write(f(value));
115    }
116}
117
118/// Writes `f(src[i])` into every slot of the two destinations.
119#[cfg_attr(feature = "simd", allow(dead_code))]
120pub(crate) fn scalar_apply_ff<T: Copy>(
121    src: &[T],
122    first: &mut [MaybeUninit<T>],
123    second: &mut [MaybeUninit<T>],
124    f: impl Fn(T) -> (T, T),
125) {
126    for ((slot_a, slot_b), &value) in first.iter_mut().zip(second.iter_mut()).zip(src.iter()) {
127        let (a, b) = f(value);
128        slot_a.write(a);
129        slot_b.write(b);
130    }
131}
132
133/// Writes `f(lhs[i], rhs[i])` into every slot of `dst`.
134#[cfg_attr(feature = "simd", allow(dead_code))]
135pub(crate) fn scalar_apply2<T: Copy>(
136    lhs: &[T],
137    rhs: &[T],
138    dst: &mut [MaybeUninit<T>],
139    f: impl Fn(T, T) -> T,
140) {
141    for ((slot, &a), &b) in dst.iter_mut().zip(lhs.iter()).zip(rhs.iter()) {
142        slot.write(f(a, b));
143    }
144}
145
146macro_rules! binary {
147        ($($name:ident, $kernel:path, $scalar:expr, $doc:literal;)*) => {
148            $(
149                #[doc = $doc]
150                #[inline]
151                pub fn $name(
152                    lhs: &[Scalar],
153                    rhs: &[Scalar],
154                    dst: &mut [MaybeUninit<Scalar>],
155                ) -> Result<(), LengthMismatch> {
156                    lengths2(lhs.len(), rhs.len(), dst.len())?;
157                    #[cfg(feature = "simd")]
158                    {
159                        let level = fearless_simd::Level::new();
160                        fearless_simd::dispatch!(level, simd => run2(simd, $kernel, lhs, rhs, dst));
161                    }
162                    #[cfg(not(feature = "simd"))]
163                    {
164                        scalar_apply2(lhs, rhs, dst, $scalar);
165                    }
166                    Ok(())
167                }
168            )*
169        };
170    }
171
172macro_rules! unary {
173        ($($name:ident, $kernel:path, $scalar:expr, $doc:literal;)*) => {
174            $(
175                #[doc = $doc]
176                #[inline]
177                pub fn $name(
178                    src: &[Scalar],
179                    dst: &mut [MaybeUninit<Scalar>],
180                ) -> Result<(), LengthMismatch> {
181                    lengths(src.len(), dst.len())?;
182                    #[cfg(feature = "simd")]
183                    {
184                        let level = fearless_simd::Level::new();
185                        fearless_simd::dispatch!(level, simd => run(simd, $kernel, src, dst));
186                    }
187                    #[cfg(not(feature = "simd"))]
188                    {
189                        scalar_apply(src, dst, $scalar);
190                    }
191                    Ok(())
192                }
193            )*
194        };
195    }
196
197macro_rules! pair {
198        ($($name:ident, $kernel:path, $scalar:expr, $doc:literal;)*) => {
199            $(
200                #[doc = $doc]
201                #[inline]
202                pub fn $name(
203                    src: &[Scalar],
204                    first: &mut [MaybeUninit<Scalar>],
205                    second: &mut [MaybeUninit<Scalar>],
206                ) -> Result<(), LengthMismatch> {
207                    lengths(src.len(), first.len())?;
208                    lengths(src.len(), second.len())?;
209                    #[cfg(feature = "simd")]
210                    {
211                        let level = fearless_simd::Level::new();
212                        fearless_simd::dispatch!(level, simd => run_ff(simd, $kernel, src, first, second));
213                    }
214                    #[cfg(not(feature = "simd"))]
215                    {
216                        scalar_apply_ff(src, first, second, $scalar);
217                    }
218                    Ok(())
219                }
220            )*
221        };
222    }
223
224/// Generates the flat-slice entry points for one scalar type.
225///
226/// `$modname` is the module to create, `$ty` the scalar, `$vec` the matching
227/// [`fearless_simd`] vector type and `$kernels` the module holding the vector kernels. Both
228/// instantiations must expose the same function names, so the tier modules drop the `f` suffix
229/// that upstream `sleef-rs` uses for `f32`.
230macro_rules! slice_api {
231    ($modname:ident, $ty:ty, $vec:ident, $kernels:ident) => {
232pub mod $modname {
233    //! Slice entry points for a scalar type.
234
235    #[cfg(feature = "simd")]
236    use super::scalar_apply;
237    use super::LengthMismatch;
238    #[cfg(not(feature = "simd"))]
239    use super::{scalar_apply, scalar_apply2, scalar_apply_ff};
240    #[cfg(feature = "simd")]
241    use crate::common::$vec;
242    use core::mem::MaybeUninit;
243
244    /// The scalar this instantiation works on; the tier macros below name it by alias so that a
245    /// single definition can serve both dtypes.
246    type Scalar = $ty;
247
248    /// The module holding the vector kernels for `Scalar`.
249    #[cfg(feature = "simd")]
250    use crate::$kernels as xkernels;
251
252    #[cfg(feature = "simd")]
253    use fearless_simd::prelude::*;
254    #[cfg(feature = "simd")]
255    use fearless_simd::Simd;
256
257    fn lengths(src: usize, dst: usize) -> Result<(), LengthMismatch> {
258        if src == dst {
259            Ok(())
260        } else {
261            Err(LengthMismatch { src, dst })
262        }
263    }
264
265    fn lengths2(lhs: usize, rhs: usize, dst: usize) -> Result<(), LengthMismatch> {
266        if lhs == rhs && lhs == dst {
267            Ok(())
268        } else {
269            Err(LengthMismatch {
270                src: lhs.min(rhs),
271                dst,
272            })
273        }
274    }
275
276    /// A unary kernel over native-width vectors.
277    #[cfg(feature = "simd")]
278    type UnaryKernel<S> = fn(S, crate::common::$vec<S>) -> crate::common::$vec<S>;
279
280    /// Applies a unary `kernel` lane-wise over `src`, writing `dst`.
281    ///
282    /// The elements past the last whole vector are handled by running the same kernel over a
283    /// padded copy, so every element goes through the kernel and the documented error bound
284    /// applies to the whole result — including the short inputs where the platform's scalar
285    /// functions are measurably worse than the kernel.
286    // `#[inline(always)]` is required by `fearless_simd`: the code called from a `dispatch!`
287    // closure is only compiled with the selected level's target features if it is inlined into
288    // that closure.
289    #[cfg(feature = "simd")]
290    #[inline(always)]
291    fn run<S: Simd>(simd: S, kernel: UnaryKernel<S>, src: &[$ty], dst: &mut [MaybeUninit<$ty>]) {
292        let n = crate::common::$vec::<S>::LEN;
293        let mut chunks = src.chunks_exact(n);
294        let mut out_chunks = dst.chunks_exact_mut(n);
295        for (chunk, out) in (&mut chunks).zip(&mut out_chunks) {
296            let v = crate::common::$vec::<S>::from_slice(simd, chunk);
297            let r = kernel(simd, v);
298            let arr = r.to_array();
299            for (slot, &value) in out.iter_mut().zip(arr.as_ref().iter()) {
300                slot.write(value);
301            }
302        }
303        let tail = chunks.remainder();
304        let out_tail = out_chunks.into_remainder();
305        if tail.is_empty() {
306            return;
307        }
308        let mut padded = $vec::<S>::splat(simd, 0.0).to_array();
309        for (slot, &value) in padded.as_mut().iter_mut().zip(tail.iter()) {
310            *slot = value;
311        }
312        let v = $vec::<S>::load_array(simd, padded);
313        let arr = kernel(simd, v).to_array();
314        for (slot, &value) in out_tail.iter_mut().zip(arr.as_ref().iter()) {
315            slot.write(value);
316        }
317    }
318
319    /// Applies a binary `kernel` lane-wise over `lhs` and `rhs`, writing `dst`.
320    #[cfg(feature = "simd")]
321    #[inline(always)]
322    fn run2<S: Simd>(
323        simd: S,
324        kernel: fn(S, crate::common::$vec<S>, crate::common::$vec<S>) -> crate::common::$vec<S>,
325        lhs: &[$ty],
326        rhs: &[$ty],
327        dst: &mut [MaybeUninit<$ty>],
328    ) {
329        let n = crate::common::$vec::<S>::LEN;
330        let mut lhs_chunks = lhs.chunks_exact(n);
331        let mut rhs_chunks = rhs.chunks_exact(n);
332        let mut out_chunks = dst.chunks_exact_mut(n);
333        for ((a, b), out) in (&mut lhs_chunks).zip(&mut rhs_chunks).zip(&mut out_chunks) {
334            let va = crate::common::$vec::<S>::from_slice(simd, a);
335            let vb = crate::common::$vec::<S>::from_slice(simd, b);
336            let r = kernel(simd, va, vb);
337            let arr = r.to_array();
338            for (slot, &value) in out.iter_mut().zip(arr.as_ref().iter()) {
339                slot.write(value);
340            }
341        }
342        let (ta, tb) = (lhs_chunks.remainder(), rhs_chunks.remainder());
343        let out_tail = out_chunks.into_remainder();
344        if ta.is_empty() {
345            return;
346        }
347        let mut pa = $vec::<S>::splat(simd, 0.0).to_array();
348        let mut pb = $vec::<S>::splat(simd, 0.0).to_array();
349        for (slot, &value) in pa.as_mut().iter_mut().zip(ta.iter()) {
350            *slot = value;
351        }
352        for (slot, &value) in pb.as_mut().iter_mut().zip(tb.iter()) {
353            *slot = value;
354        }
355        let arr = kernel(
356            simd,
357            $vec::<S>::load_array(simd, pa),
358            $vec::<S>::load_array(simd, pb),
359        )
360        .to_array();
361        for (slot, &value) in out_tail.iter_mut().zip(arr.as_ref().iter()) {
362            slot.write(value);
363        }
364    }
365
366    /// A kernel that produces two vectors from one.
367    #[cfg(feature = "simd")]
368    type FfKernel<S> =
369        fn(S, crate::common::$vec<S>) -> (crate::common::$vec<S>, crate::common::$vec<S>);
370
371    /// Applies a `kernel` returning two vectors, writing `sin` and `cos`.
372    ///
373    /// The tail is handled the same way as in [`run`]: by `scalar` when one is given, otherwise by
374    /// running the same vector kernel over a padded copy.
375    #[cfg(feature = "simd")]
376    #[inline(always)]
377    fn run_ff<S: Simd>(
378        simd: S,
379        kernel: FfKernel<S>,
380        src: &[$ty],
381        first: &mut [MaybeUninit<$ty>],
382        second: &mut [MaybeUninit<$ty>],
383    ) {
384        let n = crate::common::$vec::<S>::LEN;
385        let mut chunks = src.chunks_exact(n);
386        let mut first_chunks = first.chunks_exact_mut(n);
387        let mut second_chunks = second.chunks_exact_mut(n);
388        for ((chunk, out_a), out_b) in (&mut chunks).zip(&mut first_chunks).zip(&mut second_chunks)
389        {
390            let v = crate::common::$vec::<S>::from_slice(simd, chunk);
391            let (a, b) = kernel(simd, v);
392            let arr_a = a.to_array();
393            let arr_b = b.to_array();
394            for (slot, &value) in out_a.iter_mut().zip(arr_a.as_ref().iter()) {
395                slot.write(value);
396            }
397            for (slot, &value) in out_b.iter_mut().zip(arr_b.as_ref().iter()) {
398                slot.write(value);
399            }
400        }
401        let tail = chunks.remainder();
402        let first_tail = first_chunks.into_remainder();
403        let second_tail = second_chunks.into_remainder();
404        if tail.is_empty() {
405            return;
406        }
407        let mut padded = $vec::<S>::splat(simd, 0.0).to_array();
408        for (slot, &value) in padded.as_mut().iter_mut().zip(tail.iter()) {
409            *slot = value;
410        }
411        let (a, b) = kernel(simd, $vec::<S>::load_array(simd, padded));
412        let (arr_a, arr_b) = (a.to_array(), b.to_array());
413        for ((slot_a, slot_b), (&va, &vb)) in first_tail
414            .iter_mut()
415            .zip(second_tail.iter_mut())
416            .zip(arr_a.as_ref().iter().zip(arr_b.as_ref().iter()))
417        {
418            slot_a.write(va);
419            slot_b.write(vb);
420        }
421    }
422
423
424
425    unary! {
426        exp,        xkernels::u10::exp,        <$ty>::exp,      "Natural exponential function; 1.0 ULP.";
427        exp2,       xkernels::u10::exp2,       <$ty>::exp2,     "Base-2 exponential function; 1.0 ULP.";
428        exp10,      xkernels::u10::exp10,      |v: $ty| <$ty>::powf(10.0, v),    "Base-10 exponential function; 1.09 ULP.";
429        expm1,      xkernels::u10::expm1,      <$ty>::exp_m1,   "Natural exponential function minus one; 1.0 ULP.";
430        log,        xkernels::u10::log,        <$ty>::ln,       "Natural logarithm; 1.0 ULP.";
431        log2,       xkernels::u10::log2,       <$ty>::log2,     "Base-2 logarithm; 1.0 ULP.";
432        log10,      xkernels::u10::log10,      <$ty>::log10,    "Base-10 logarithm; 1.0 ULP.";
433        log1p,      xkernels::u10::log1p,      <$ty>::ln_1p,    "Logarithm of one plus the argument; 1.0 ULP.";
434        sin,        xkernels::u10::sin,        <$ty>::sin,      "Sine function; 1.0 ULP.";
435        cos,        xkernels::u10::cos,        <$ty>::cos,      "Cosine function; 1.0 ULP.";
436        tan,        xkernels::u10::tan,        <$ty>::tan,      "Tangent function; 1.0 ULP.";
437        asin,       xkernels::u10::asin,       <$ty>::asin,     "Arc sine function; 1.0 ULP.";
438        acos,       xkernels::u10::acos,       <$ty>::acos,     "Arc cosine function; 1.0 ULP.";
439        atan,       xkernels::u10::atan,       <$ty>::atan,     "Arc tangent function; 1.0 ULP.";
440        sinh,       xkernels::u10::sinh,       <$ty>::sinh,     "Hyperbolic sine function; 1.0 ULP.";
441        cosh,       xkernels::u10::cosh,       <$ty>::cosh,     "Hyperbolic cosine function; 1.0 ULP.";
442        tanh,       xkernels::u10::tanh,       <$ty>::tanh,     "Hyperbolic tangent function; 1.0 ULP.";
443        asinh,      xkernels::u10::asinh,      <$ty>::asinh,    "Inverse hyperbolic sine function; 1.0 ULP.";
444        acosh,      xkernels::u10::acosh,      <$ty>::acosh,    "Inverse hyperbolic cosine function; 1.0 ULP.";
445        atanh,      xkernels::u10::atanh,      <$ty>::atanh,    "Inverse hyperbolic tangent function; 1.0 ULP.";
446        cbrt,       xkernels::u10::cbrt,       <$ty>::cbrt,     "Cube root function; 1.0 ULP.";
447        sin_deterministic, xkernels::u10::sin_deterministic, <$ty>::sin,
448            "Sine, bitwise identical across lanes and platforms; 1.0 ULP.";
449        cos_deterministic, xkernels::u10::cos_deterministic, <$ty>::cos,
450            "Cosine, bitwise identical across lanes and platforms; 1.0 ULP.";
451        tan_deterministic, xkernels::u10::tan_deterministic, <$ty>::tan,
452            "Tangent, bitwise identical across lanes and platforms; 1.0 ULP.";
453    }
454
455
456
457    unary! {
458        sin_u35,   xkernels::u35::sin,   <$ty>::sin,    "Sine function, 3.5 ULP tier.";
459        cos_u35,   xkernels::u35::cos,   <$ty>::cos,    "Cosine function, 3.5 ULP tier.";
460        tan_u35,   xkernels::u35::tan,   <$ty>::tan,    "Tangent function, 3.5 ULP tier.";
461        asin_u35,  xkernels::u35::asin,  <$ty>::asin,   "Arc sine function, 3.5 ULP tier.";
462        acos_u35,  xkernels::u35::acos,  <$ty>::acos,   "Arc cosine function, 3.5 ULP tier.";
463        atan_u35,  xkernels::u35::atan,  <$ty>::atan,   "Arc tangent function, 3.5 ULP tier.";
464        sinh_u35,  xkernels::u35::sinh,  <$ty>::sinh,   "Hyperbolic sine, 3.5 ULP tier.";
465        cosh_u35,  xkernels::u35::cosh,  <$ty>::cosh,   "Hyperbolic cosine, 3.5 ULP tier.";
466        tanh_u35,  xkernels::u35::tanh,  <$ty>::tanh,   "Hyperbolic tangent, 3.5 ULP tier.";
467        log_u35,   xkernels::u35::log,   <$ty>::ln,     "Natural logarithm, 3.5 ULP tier.";
468        log2_u35,  xkernels::u35::log2,  <$ty>::log2,   "Base-2 logarithm, 3.5 ULP tier.";
469        exp2_u35,  xkernels::u35::exp2,  <$ty>::exp2,   "Base-2 exponential, 3.5 ULP tier.";
470        exp10_u35, xkernels::u35::exp10, |v: $ty| <$ty>::powf(10.0, v), "Base-10 exponential, 3.5 ULP tier.";
471        cbrt_u35,  xkernels::u35::cbrt,  <$ty>::cbrt,   "Cube root, 3.5 ULP tier.";
472        sin_deterministic_u35, xkernels::u35::sin_deterministic, <$ty>::sin,
473            "Sine, lane-order independent, 3.5 ULP tier.";
474        cos_deterministic_u35, xkernels::u35::cos_deterministic, <$ty>::cos,
475            "Cosine, lane-order independent, 3.5 ULP tier.";
476        tan_deterministic_u35, xkernels::u35::tan_deterministic, <$ty>::tan,
477            "Tangent, lane-order independent, 3.5 ULP tier.";
478    }
479
480    /// Square root; `0.5001 ULP`. Equivalent to the hardware square root.
481    #[inline]
482    pub fn sqrt(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
483        lengths(src.len(), dst.len())?;
484        scalar_apply(src, dst, <$ty>::sqrt);
485        Ok(())
486    }
487
488
489
490    pair! {
491        sincos, xkernels::u10::sincos, |v: $ty| (v.sin(), v.cos()),
492            "Sine and cosine evaluated together; 1.0 ULP.";
493        sincos_deterministic, xkernels::u10::sincos_deterministic, |v: $ty| (v.sin(), v.cos()),
494            "Sine and cosine together, lane-order independent; 1.0 ULP.";
495        sincos_u35, xkernels::u35::sincos, |v: $ty| (v.sin(), v.cos()),
496            "Sine and cosine evaluated together, 3.5 ULP tier.";
497        sincos_deterministic_u35, xkernels::u35::sincos_deterministic, |v: $ty| (v.sin(), v.cos()),
498            "Sine and cosine together, lane-order independent, 3.5 ULP tier.";
499    }
500
501    /// Sine and cosine of `pi * x` together; `0.506 ULP`.
502    ///
503    /// There is no scalar implementation in the standard library that is accurate enough for
504    /// large arguments, so the tail uses the vector kernel over a padded copy.
505    #[cfg(feature = "simd")]
506    #[inline]
507    pub fn sincospi(
508        src: &[$ty],
509        first: &mut [MaybeUninit<$ty>],
510        second: &mut [MaybeUninit<$ty>],
511    ) -> Result<(), LengthMismatch> {
512        lengths(src.len(), first.len())?;
513        lengths(src.len(), second.len())?;
514        let level = fearless_simd::Level::new();
515        fearless_simd::dispatch!(level, simd => run_ff(simd, xkernels::u05::sincospi, src, first, second));
516        Ok(())
517    }
518
519    /// Sine and cosine of `pi * x` together, 3.5 ULP tier.
520    #[cfg(feature = "simd")]
521    #[inline]
522    pub fn sincospi_u35(
523        src: &[$ty],
524        first: &mut [MaybeUninit<$ty>],
525        second: &mut [MaybeUninit<$ty>],
526    ) -> Result<(), LengthMismatch> {
527        lengths(src.len(), first.len())?;
528        lengths(src.len(), second.len())?;
529        let level = fearless_simd::Level::new();
530        fearless_simd::dispatch!(level, simd => run_ff(simd, xkernels::u35::sincospi, src, first, second));
531        Ok(())
532    }
533
534
535
536    binary! {
537        pow,    xkernels::u10::pow,    |a: $ty, b: $ty| <$ty>::powf(a, b),  "Argument raised to an argument power; 1.0 ULP.";
538        atan2,  xkernels::u10::atan2,  |a: $ty, b: $ty| <$ty>::atan2(a, b), "Arc tangent of two arguments; 1.0 ULP.";
539    }
540
541    /// Euclidean distance in two dimensions; `0.5001 ULP`.
542    #[cfg(feature = "simd")]
543    #[inline]
544    pub fn hypot(
545        lhs: &[$ty],
546        rhs: &[$ty],
547        dst: &mut [MaybeUninit<$ty>],
548    ) -> Result<(), LengthMismatch> {
549        lengths2(lhs.len(), rhs.len(), dst.len())?;
550        let level = fearless_simd::Level::new();
551        fearless_simd::dispatch!(level, simd => run2(simd, xkernels::u05::hypot, lhs, rhs, dst));
552        Ok(())
553    }
554
555    /// Euclidean distance in two dimensions; scalar implementation.
556    #[cfg(not(feature = "simd"))]
557    #[inline]
558    pub fn hypot(
559        lhs: &[$ty],
560        rhs: &[$ty],
561        dst: &mut [MaybeUninit<$ty>],
562    ) -> Result<(), LengthMismatch> {
563        lengths2(lhs.len(), rhs.len(), dst.len())?;
564        scalar_apply2(lhs, rhs, dst, <$ty>::hypot);
565        Ok(())
566    }
567
568    /// Error function; 1.0 ULP.
569    #[cfg(feature = "simd")]
570    #[inline]
571    pub fn erf(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
572        lengths(src.len(), dst.len())?;
573        let level = fearless_simd::Level::new();
574        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u10::erf, src, dst));
575        Ok(())
576    }
577
578    /// Complementary error function; `max(1.5, 2.5) ULP`.
579    #[cfg(feature = "simd")]
580    #[inline]
581    pub fn erfc(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
582        lengths(src.len(), dst.len())?;
583        let level = fearless_simd::Level::new();
584        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u15::erfc, src, dst));
585        Ok(())
586    }
587
588    /// Gamma function; 1.0 ULP.
589    #[cfg(feature = "simd")]
590    #[inline]
591    pub fn tgamma(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
592        lengths(src.len(), dst.len())?;
593        let level = fearless_simd::Level::new();
594        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u10::tgamma, src, dst));
595        Ok(())
596    }
597
598    /// Logarithm of the absolute gamma function; 1.0 ULP.
599    #[cfg(feature = "simd")]
600    #[inline]
601    pub fn lgamma(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
602        lengths(src.len(), dst.len())?;
603        let level = fearless_simd::Level::new();
604        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u10::lgamma, src, dst));
605        Ok(())
606    }
607
608    /// Sine of `pi * x`; `0.506 ULP`.
609    #[cfg(feature = "simd")]
610    #[inline]
611    pub fn sinpi(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
612        lengths(src.len(), dst.len())?;
613        let level = fearless_simd::Level::new();
614        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u05::sinpi, src, dst));
615        Ok(())
616    }
617
618    /// Cosine of `pi * x`; `0.506 ULP`.
619    #[cfg(feature = "simd")]
620    #[inline]
621    pub fn cospi(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
622        lengths(src.len(), dst.len())?;
623        let level = fearless_simd::Level::new();
624        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u05::cospi, src, dst));
625        Ok(())
626    }
627}
628
629impl ElementwiseMath for $ty {
630    fn exp(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
631        self::$modname::exp(src, dst)
632    }
633    fn exp2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
634        self::$modname::exp2(src, dst)
635    }
636    fn exp10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
637        self::$modname::exp10(src, dst)
638    }
639    fn expm1(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
640        self::$modname::expm1(src, dst)
641    }
642    fn log(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
643        self::$modname::log(src, dst)
644    }
645    fn log2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
646        self::$modname::log2(src, dst)
647    }
648    fn log10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
649        self::$modname::log10(src, dst)
650    }
651    fn log1p(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
652        self::$modname::log1p(src, dst)
653    }
654    fn sin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
655        self::$modname::sin(src, dst)
656    }
657    fn cos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
658        self::$modname::cos(src, dst)
659    }
660    fn tan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
661        self::$modname::tan(src, dst)
662    }
663    fn asin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
664        self::$modname::asin(src, dst)
665    }
666    fn acos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
667        self::$modname::acos(src, dst)
668    }
669    fn atan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
670        self::$modname::atan(src, dst)
671    }
672    fn sinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
673        self::$modname::sinh(src, dst)
674    }
675    fn cosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
676        self::$modname::cosh(src, dst)
677    }
678    fn tanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
679        self::$modname::tanh(src, dst)
680    }
681    fn asinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
682        self::$modname::asinh(src, dst)
683    }
684    fn acosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
685        self::$modname::acosh(src, dst)
686    }
687    fn atanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
688        self::$modname::atanh(src, dst)
689    }
690    fn cbrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
691        self::$modname::cbrt(src, dst)
692    }
693    fn sqrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
694        self::$modname::sqrt(src, dst)
695    }
696    fn pow(
697        lhs: &[Self],
698        rhs: &[Self],
699        dst: &mut [MaybeUninit<Self>],
700    ) -> Result<(), LengthMismatch> {
701        self::$modname::pow(lhs, rhs, dst)
702    }
703    fn atan2(
704        lhs: &[Self],
705        rhs: &[Self],
706        dst: &mut [MaybeUninit<Self>],
707    ) -> Result<(), LengthMismatch> {
708        self::$modname::atan2(lhs, rhs, dst)
709    }
710    fn hypot(
711        lhs: &[Self],
712        rhs: &[Self],
713        dst: &mut [MaybeUninit<Self>],
714    ) -> Result<(), LengthMismatch> {
715        self::$modname::hypot(lhs, rhs, dst)
716    }
717    fn sincos(
718        src: &[Self],
719        sin_dst: &mut [MaybeUninit<Self>],
720        cos_dst: &mut [MaybeUninit<Self>],
721    ) -> Result<(), LengthMismatch> {
722        self::$modname::sincos(src, sin_dst, cos_dst)
723    }
724}
725    };
726}
727
728slice_api!(f64, f64, F64s, f64x);
729slice_api!(f32, f32, F32s, f32x);