Skip to main content

wide/
f64x4_.rs

1use super::*;
2
3pick! {
4  if #[cfg(target_feature="avx")] {
5    #[derive(Default, Clone, Copy, PartialEq)]
6    #[repr(C, align(32))]
7    pub struct f64x4 { pub(crate) avx: m256d }
8  } else {
9    #[derive(Default, Clone, Copy, PartialEq)]
10    #[repr(C, align(32))]
11    pub struct f64x4 { pub(crate) a: f64x2, pub(crate) b: f64x2 }
12  }
13}
14
15macro_rules! const_f64_as_f64x4 {
16  ($i:ident, $f:expr) => {
17    #[allow(non_upper_case_globals)]
18    pub const $i: f64x4 = f64x4::new([$f; 4]);
19  };
20}
21
22impl f64x4 {
23  const_f64_as_f64x4!(ONE, 1.0);
24  const_f64_as_f64x4!(ZERO, 0.0);
25  const_f64_as_f64x4!(HALF, 0.5);
26  const_f64_as_f64x4!(EPSILON, f64::EPSILON);
27  const_f64_as_f64x4!(MIN, f64::MIN);
28  const_f64_as_f64x4!(MIN_POSITIVE, f64::MIN_POSITIVE);
29  const_f64_as_f64x4!(MAX, f64::MAX);
30  const_f64_as_f64x4!(NAN, f64::NAN);
31  const_f64_as_f64x4!(INFINITY, f64::INFINITY);
32  const_f64_as_f64x4!(NEG_INFINITY, f64::NEG_INFINITY);
33  const_f64_as_f64x4!(E, core::f64::consts::E);
34  const_f64_as_f64x4!(FRAC_1_PI, core::f64::consts::FRAC_1_PI);
35  const_f64_as_f64x4!(FRAC_2_PI, core::f64::consts::FRAC_2_PI);
36  const_f64_as_f64x4!(FRAC_2_SQRT_PI, core::f64::consts::FRAC_2_SQRT_PI);
37  const_f64_as_f64x4!(FRAC_1_SQRT_2, core::f64::consts::FRAC_1_SQRT_2);
38  const_f64_as_f64x4!(FRAC_PI_2, core::f64::consts::FRAC_PI_2);
39  const_f64_as_f64x4!(FRAC_PI_3, core::f64::consts::FRAC_PI_3);
40  const_f64_as_f64x4!(FRAC_PI_4, core::f64::consts::FRAC_PI_4);
41  const_f64_as_f64x4!(FRAC_PI_6, core::f64::consts::FRAC_PI_6);
42  const_f64_as_f64x4!(FRAC_PI_8, core::f64::consts::FRAC_PI_8);
43  const_f64_as_f64x4!(LN_2, core::f64::consts::LN_2);
44  const_f64_as_f64x4!(LN_10, core::f64::consts::LN_10);
45  const_f64_as_f64x4!(LOG2_E, core::f64::consts::LOG2_E);
46  const_f64_as_f64x4!(LOG10_E, core::f64::consts::LOG10_E);
47  const_f64_as_f64x4!(LOG10_2, core::f64::consts::LOG10_2);
48  const_f64_as_f64x4!(LOG2_10, core::f64::consts::LOG2_10);
49  const_f64_as_f64x4!(PI, core::f64::consts::PI);
50  const_f64_as_f64x4!(SQRT_2, core::f64::consts::SQRT_2);
51  const_f64_as_f64x4!(TAU, core::f64::consts::TAU);
52}
53
54unsafe impl Zeroable for f64x4 {}
55unsafe impl Pod for f64x4 {}
56
57impl AlignTo for f64x4 {
58  type Elem = f64;
59}
60
61impl Add for f64x4 {
62  type Output = Self;
63  #[inline]
64  fn add(self, rhs: Self) -> Self::Output {
65    pick! {
66      if #[cfg(target_feature="avx")] {
67        Self { avx: add_m256d(self.avx, rhs.avx) }
68      } else {
69        Self {
70          a : self.a.add(rhs.a),
71          b : self.b.add(rhs.b),
72        }
73      }
74    }
75  }
76}
77
78impl Sub for f64x4 {
79  type Output = Self;
80  #[inline]
81  fn sub(self, rhs: Self) -> Self::Output {
82    pick! {
83      if #[cfg(target_feature="avx")] {
84        Self { avx: sub_m256d(self.avx, rhs.avx) }
85      } else {
86        Self {
87          a : self.a.sub(rhs.a),
88          b : self.b.sub(rhs.b),
89        }
90      }
91    }
92  }
93}
94
95impl Mul for f64x4 {
96  type Output = Self;
97  #[inline]
98  fn mul(self, rhs: Self) -> Self::Output {
99    pick! {
100      if #[cfg(target_feature="avx")] {
101        Self { avx: mul_m256d(self.avx, rhs.avx) }
102      } else {
103        Self {
104          a : self.a.mul(rhs.a),
105          b : self.b.mul(rhs.b),
106        }
107      }
108    }
109  }
110}
111
112impl Div for f64x4 {
113  type Output = Self;
114  #[inline]
115  fn div(self, rhs: Self) -> Self::Output {
116    pick! {
117      if #[cfg(target_feature="avx")] {
118        Self { avx: div_m256d(self.avx, rhs.avx) }
119      } else {
120        Self {
121          a : self.a.div(rhs.a),
122          b : self.b.div(rhs.b),
123        }
124      }
125    }
126  }
127}
128
129impl Rem for f64x4 {
130  type Output = Self;
131  #[inline]
132  fn rem(self, rhs: Self) -> Self::Output {
133    Self::new([
134      self.to_array()[0] % rhs.to_array()[0],
135      self.to_array()[1] % rhs.to_array()[1],
136      self.to_array()[2] % rhs.to_array()[2],
137      self.to_array()[3] % rhs.to_array()[3],
138    ])
139  }
140}
141
142impl Neg for f64x4 {
143  type Output = Self;
144  #[inline]
145  fn neg(self) -> Self::Output {
146    pick! {
147      if #[cfg(target_feature="avx")] {
148        Self { avx: bitxor_m256d(self.avx, Self::splat(-0.0).avx) }
149      } else {
150        Self {
151          a : self.a.neg(),
152          b : self.b.neg(),
153        }
154      }
155    }
156  }
157}
158
159impl Add<f64> for f64x4 {
160  type Output = Self;
161  #[inline]
162  fn add(self, rhs: f64) -> Self::Output {
163    self.add(Self::splat(rhs))
164  }
165}
166
167impl Sub<f64> for f64x4 {
168  type Output = Self;
169  #[inline]
170  fn sub(self, rhs: f64) -> Self::Output {
171    self.sub(Self::splat(rhs))
172  }
173}
174
175impl Mul<f64> for f64x4 {
176  type Output = Self;
177  #[inline]
178  fn mul(self, rhs: f64) -> Self::Output {
179    self.mul(Self::splat(rhs))
180  }
181}
182
183impl Div<f64> for f64x4 {
184  type Output = Self;
185  #[inline]
186  fn div(self, rhs: f64) -> Self::Output {
187    self.div(Self::splat(rhs))
188  }
189}
190
191impl Rem<f64> for f64x4 {
192  type Output = Self;
193  #[inline]
194  fn rem(self, rhs: f64) -> Self::Output {
195    self.rem(Self::splat(rhs))
196  }
197}
198
199impl Add<f64x4> for f64 {
200  type Output = f64x4;
201  #[inline]
202  fn add(self, rhs: f64x4) -> Self::Output {
203    f64x4::splat(self).add(rhs)
204  }
205}
206
207impl Sub<f64x4> for f64 {
208  type Output = f64x4;
209  #[inline]
210  fn sub(self, rhs: f64x4) -> Self::Output {
211    f64x4::splat(self).sub(rhs)
212  }
213}
214
215impl Mul<f64x4> for f64 {
216  type Output = f64x4;
217  #[inline]
218  fn mul(self, rhs: f64x4) -> Self::Output {
219    f64x4::splat(self).mul(rhs)
220  }
221}
222
223impl Div<f64x4> for f64 {
224  type Output = f64x4;
225  #[inline]
226  fn div(self, rhs: f64x4) -> Self::Output {
227    f64x4::splat(self).div(rhs)
228  }
229}
230
231impl Rem<f64x4> for f64 {
232  type Output = f64x4;
233  #[inline]
234  fn rem(self, rhs: f64x4) -> Self::Output {
235    f64x4::splat(self).rem(rhs)
236  }
237}
238
239impl BitAnd for f64x4 {
240  type Output = Self;
241  #[inline]
242  fn bitand(self, rhs: Self) -> Self::Output {
243    pick! {
244      if #[cfg(target_feature="avx")] {
245        Self { avx: bitand_m256d(self.avx, rhs.avx) }
246      } else {
247        Self {
248          a : self.a.bitand(rhs.a),
249          b : self.b.bitand(rhs.b),
250        }
251      }
252    }
253  }
254}
255
256impl BitOr for f64x4 {
257  type Output = Self;
258  #[inline]
259  fn bitor(self, rhs: Self) -> Self::Output {
260    pick! {
261      if #[cfg(target_feature="avx")] {
262        Self { avx: bitor_m256d(self.avx, rhs.avx) }
263      } else {
264        Self {
265          a : self.a.bitor(rhs.a),
266          b : self.b.bitor(rhs.b),
267        }
268      }
269    }
270  }
271}
272
273impl BitXor for f64x4 {
274  type Output = Self;
275  #[inline]
276  fn bitxor(self, rhs: Self) -> Self::Output {
277    pick! {
278      if #[cfg(target_feature="avx")] {
279        Self { avx: bitxor_m256d(self.avx, rhs.avx) }
280      } else {
281        Self {
282          a : self.a.bitxor(rhs.a),
283          b : self.b.bitxor(rhs.b),
284        }
285      }
286    }
287  }
288}
289
290#[expect(deprecated)]
291impl CmpEq for f64x4 {
292  type Output = Self;
293  #[inline]
294  fn simd_eq(self, rhs: Self) -> Self::Output {
295    pick! {
296      if #[cfg(target_feature="avx")]{
297        Self { avx: cmp_op_mask_m256d::<{cmp_op!(EqualOrdered)}>(self.avx, rhs.avx) }
298      } else {
299        Self {
300          a : self.a.simd_eq(rhs.a),
301          b : self.b.simd_eq(rhs.b),
302        }
303      }
304    }
305  }
306}
307
308#[expect(deprecated)]
309impl CmpGe for f64x4 {
310  type Output = Self;
311  #[inline]
312  fn simd_ge(self, rhs: Self) -> Self::Output {
313    pick! {
314      if #[cfg(target_feature="avx")]{
315        Self { avx: cmp_op_mask_m256d::<{cmp_op!(GreaterEqualOrdered)}>(self.avx, rhs.avx) }
316      } else {
317        Self {
318          a : self.a.simd_ge(rhs.a),
319          b : self.b.simd_ge(rhs.b),
320        }
321      }
322    }
323  }
324}
325
326#[expect(deprecated)]
327impl CmpGt for f64x4 {
328  type Output = Self;
329  #[inline]
330  fn simd_gt(self, rhs: Self) -> Self::Output {
331    pick! {
332      if #[cfg(target_feature="avx")]{
333        Self { avx: cmp_op_mask_m256d::<{cmp_op!( GreaterThanOrdered)}>(self.avx, rhs.avx) }
334      } else {
335        Self {
336          a : self.a.simd_gt(rhs.a),
337          b : self.b.simd_gt(rhs.b),
338        }
339      }
340    }
341  }
342}
343
344#[expect(deprecated)]
345impl CmpNe for f64x4 {
346  type Output = Self;
347  #[inline]
348  fn simd_ne(self, rhs: Self) -> Self::Output {
349    pick! {
350      if #[cfg(target_feature="avx")]{
351        Self { avx: cmp_op_mask_m256d::<{cmp_op!(NotEqualUnordered)}>(self.avx, rhs.avx) }
352      } else {
353        Self {
354          a : self.a.simd_ne(rhs.a),
355          b : self.b.simd_ne(rhs.b),
356        }
357      }
358    }
359  }
360}
361
362#[expect(deprecated)]
363impl CmpLe for f64x4 {
364  type Output = Self;
365  #[inline]
366  fn simd_le(self, rhs: Self) -> Self::Output {
367    pick! {
368      if #[cfg(target_feature="avx")]{
369        Self { avx: cmp_op_mask_m256d::<{cmp_op!(LessEqualOrdered)}>(self.avx, rhs.avx) }
370      } else {
371        Self {
372          a : self.a.simd_le(rhs.a),
373          b : self.b.simd_le(rhs.b),
374        }
375      }
376    }
377  }
378}
379
380#[expect(deprecated)]
381impl CmpLt for f64x4 {
382  type Output = Self;
383  #[inline]
384  fn simd_lt(self, rhs: Self) -> Self::Output {
385    pick! {
386      if #[cfg(target_feature="avx")]{
387        Self { avx: cmp_op_mask_m256d::<{cmp_op!(LessThanOrdered)}>(self.avx, rhs.avx) }
388      } else {
389        Self {
390          a : self.a.simd_lt(rhs.a),
391          b : self.b.simd_lt(rhs.b),
392        }
393      }
394    }
395  }
396}
397
398impl f64x4 {
399  #[inline]
400  #[must_use]
401  pub const fn new(array: [f64; 4]) -> Self {
402    unsafe { core::mem::transmute(array) }
403  }
404
405  simd_comparison_fns!();
406
407  #[inline]
408  #[must_use]
409  pub fn blend(self, t: Self, f: Self) -> Self {
410    pick! {
411      if #[cfg(target_feature="avx")] {
412        Self { avx: blend_varying_m256d(f.avx, t.avx, self.avx) }
413      } else {
414        Self {
415          a : self.a.blend(t.a, f.a),
416          b : self.b.blend(t.b, f.b),
417        }
418      }
419    }
420  }
421
422  #[inline]
423  #[must_use]
424  pub fn abs(self) -> Self {
425    pick! {
426      if #[cfg(target_feature="avx")] {
427        let non_sign_bits = f64x4::from(f64::from_bits(i64::MAX as u64));
428        self & non_sign_bits
429      } else {
430        Self {
431          a : self.a.abs(),
432          b : self.b.abs(),
433        }
434      }
435    }
436  }
437
438  #[inline]
439  #[must_use]
440  pub fn signum(self) -> Self {
441    let result = Self::ONE | self & -Self::ZERO;
442
443    self.is_nan().blend(self, result)
444  }
445
446  #[inline]
447  #[must_use]
448  pub fn floor(self) -> Self {
449    pick! {
450      if #[cfg(target_feature="avx")] {
451        Self { avx: floor_m256d(self.avx) }
452      } else {
453        Self {
454          a : self.a.floor(),
455          b : self.b.floor(),
456        }
457      }
458    }
459  }
460  #[inline]
461  #[must_use]
462  pub fn ceil(self) -> Self {
463    pick! {
464      if #[cfg(target_feature="avx")] {
465        Self { avx: ceil_m256d(self.avx) }
466      } else {
467        Self {
468          a : self.a.ceil(),
469          b : self.b.ceil(),
470        }
471      }
472    }
473  }
474
475  /// Calculates the lanewise maximum of both vectors. This is a faster
476  /// implementation than `max`, but it doesn't specify any behavior if NaNs are
477  /// involved.
478  #[inline]
479  #[must_use]
480  pub fn fast_max(self, rhs: Self) -> Self {
481    pick! {
482      if #[cfg(target_feature="avx")] {
483        Self { avx: max_m256d(self.avx, rhs.avx) }
484      } else {
485        Self {
486          a : self.a.fast_max(rhs.a),
487          b : self.b.fast_max(rhs.b),
488        }
489      }
490    }
491  }
492
493  /// Calculates the lanewise maximum of both vectors. If either lane is NaN,
494  /// the other lane gets chosen. Use `fast_max` for a faster implementation
495  /// that doesn't handle NaNs.
496  #[inline]
497  #[must_use]
498  pub fn max(self, rhs: Self) -> Self {
499    pick! {
500      if #[cfg(target_feature="avx")] {
501        // max_m256d seems to do rhs < self ? self : rhs. So if there's any NaN
502        // involved, it chooses rhs, so we need to specifically check rhs for
503        // NaN.
504        rhs.is_nan().blend(self, Self { avx: max_m256d(self.avx, rhs.avx) })
505      } else {
506        Self {
507          a : self.a.max(rhs.a),
508          b : self.b.max(rhs.b),
509        }
510      }
511    }
512  }
513
514  /// Calculates the lanewise minimum of both vectors. This is a faster
515  /// implementation than `min`, but it doesn't specify any behavior if NaNs are
516  /// involved.
517  #[inline]
518  #[must_use]
519  pub fn fast_min(self, rhs: Self) -> Self {
520    pick! {
521      if #[cfg(target_feature="avx")] {
522        Self { avx: min_m256d(self.avx, rhs.avx) }
523      } else {
524        Self {
525          a : self.a.fast_min(rhs.a),
526          b : self.b.fast_min(rhs.b),
527        }
528      }
529    }
530  }
531
532  /// Calculates the lanewise minimum of both vectors. If either lane is NaN,
533  /// the other lane gets chosen. Use `fast_min` for a faster implementation
534  /// that doesn't handle NaNs.
535  #[inline]
536  #[must_use]
537  pub fn min(self, rhs: Self) -> Self {
538    pick! {
539      if #[cfg(target_feature="avx")] {
540        // min_m256d seems to do rhs < self ? self : rhs. So if there's any NaN
541        // involved, it chooses rhs, so we need to specifically check rhs for
542        // NaN.
543        rhs.is_nan().blend(self, Self { avx: min_m256d(self.avx, rhs.avx) })
544      } else {
545        Self {
546          a : self.a.min(rhs.a),
547          b : self.b.min(rhs.b),
548        }
549      }
550    }
551  }
552
553  /// Restrict a value to a certain interval unless it is NaN.
554  ///
555  /// If `self` is NaN, or `min` is NaN, or `max` is NaN, the result is NaN.
556  /// If `min > max`, the result is `min`, since `fast_max(min)` dominates.
557  #[inline]
558  #[must_use]
559  pub fn clamp(self, min: Self, max: Self) -> Self {
560    let is_nan = self.is_nan() | min.is_nan() | max.is_nan();
561    let clamped = self.fast_min(max).fast_max(min);
562    is_nan.blend(Self::splat(f64::NAN), clamped)
563  }
564
565  /// Restrict a value to a certain interval unless it is NaN.
566  ///
567  /// Avoids NaN detection; same speed as the old `clamp` prior to IEEE 754-2019
568  /// compliance. Does not specify any
569  /// behavior if NaNs are involved, and if `min > max` the result is
570  /// unspecified.
571  #[inline]
572  #[must_use]
573  pub fn fast_clamp(self, min: Self, max: Self) -> Self {
574    pick! {
575      if #[cfg(target_feature="avx")] {
576        // For both `min_m256d` and `max_m256d` if any input is NaN, `rhs` gets
577        // chosen. For `self` to be chosen, `self` must be the second argument.
578        Self { avx: min_m256d(max.avx, max_m256d(min.avx, self.avx)) }
579      } else {
580        Self {
581          a: self.a.fast_clamp(min.a, max.a),
582          b: self.b.fast_clamp(min.b, max.b),
583        }
584      }
585    }
586  }
587
588  #[inline]
589  #[must_use]
590  pub fn midpoint(self, other: Self) -> Self {
591    (self + other) * 0.5
592  }
593
594  #[inline]
595  #[must_use]
596  pub fn is_nan(self) -> Self {
597    pick! {
598      if #[cfg(target_feature="avx")] {
599        Self { avx: cmp_op_mask_m256d::<{cmp_op!(Unordered)}>(self.avx, self.avx ) }
600      } else {
601        Self {
602          a : self.a.is_nan(),
603          b : self.b.is_nan(),
604        }
605      }
606    }
607  }
608
609  #[inline]
610  #[must_use]
611  pub fn is_finite(self) -> Self {
612    let shifted_exp_mask = u64x4::from(0xFFE0000000000000);
613    let u: u64x4 = cast(self);
614    let shift_u = u << 1_u64;
615    let out = !(shift_u & shifted_exp_mask).simd_eq(shifted_exp_mask);
616    cast(out)
617  }
618
619  #[inline]
620  #[must_use]
621  pub fn is_inf(self) -> Self {
622    let shifted_inf = u64x4::from(0xFFE0000000000000);
623    let u: u64x4 = cast(self);
624    let shift_u = u << 1_u64;
625    let out = (shift_u).simd_eq(shifted_inf);
626    cast(out)
627  }
628
629  #[inline]
630  #[must_use]
631  pub fn round(self) -> Self {
632    pick! {
633      if #[cfg(target_feature="avx")] {
634        Self { avx: round_m256d::<{round_op!(Nearest)}>(self.avx) }
635      } else {
636        Self {
637          a : self.a.round(),
638          b : self.b.round(),
639        }
640      }
641    }
642  }
643
644  #[inline]
645  #[must_use]
646  pub fn fast_round_int(self) -> i64x4 {
647    pick! {
648      if #[cfg(all(target_feature="avx512dq", target_feature="avx512vl"))] {
649        #[cfg(target_arch = "x86")]
650        use core::arch::x86::_mm256_cvtpd_epi64;
651        #[cfg(target_arch = "x86_64")]
652        use core::arch::x86_64::_mm256_cvtpd_epi64;
653
654        // TODO(safe_arch): Add `_mm256_cvtpd_epi64`.
655        cast(m256i(unsafe { _mm256_cvtpd_epi64(self.avx.0) }))
656      } else {
657        let [a, b]: [f64x2; 2] = cast(self);
658        cast([a.fast_round_int(), b.fast_round_int()])
659      }
660    }
661  }
662
663  #[inline]
664  #[must_use]
665  pub fn round_int(self) -> i64x4 {
666    pick! {
667      if #[cfg(all(target_feature="avx512dq", target_feature="avx512vl"))] {
668        #[cfg(target_arch = "x86")]
669        use core::arch::x86::_mm256_cvtpd_epi64;
670        #[cfg(target_arch = "x86_64")]
671        use core::arch::x86_64::_mm256_cvtpd_epi64;
672
673        // Based on: https://github.com/v8/v8/blob/210987a552a2bf2a854b0baa9588a5959ff3979d/src/codegen/shared-ia32-x64/macro-assembler-shared-ia32-x64.h#L489-L504
674        let non_nan_mask = self.simd_eq(self);
675        let non_nan = self & non_nan_mask;
676        let flip_to_max: i64x4 = cast(self.simd_ge(Self::splat(9223372036854775808.0)));
677
678        // TODO(safe_arch): Add `_mm256_cvtpd_epi64`.
679        let cast: i64x4 = cast(m256i(unsafe { _mm256_cvtpd_epi64(non_nan.avx.0) }));
680        flip_to_max ^ cast
681      } else {
682        let [a, b]: [f64x2; 2] = cast(self);
683        cast([a.round_int(), b.round_int()])
684      }
685    }
686  }
687
688  #[inline]
689  #[must_use]
690  pub fn trunc(self) -> Self {
691    pick! {
692      if #[cfg(target_feature="avx")] {
693        Self { avx: round_m256d::<{round_op!(Zero)}>(self.avx) }
694      } else {
695        Self {
696          a : self.a.trunc(),
697          b : self.b.trunc(),
698        }
699      }
700    }
701  }
702
703  /// Truncates each lane into an integer. This is a faster implementation than
704  /// `trunc_int`, but it doesn't handle out of range values or NaNs. For those
705  /// values you get implementation defined behavior.
706  #[inline]
707  #[must_use]
708  pub fn fast_trunc_int(self) -> i64x4 {
709    pick! {
710      if #[cfg(all(target_feature="avx512dq", target_feature="avx512vl"))] {
711        #[cfg(target_arch = "x86")]
712        use core::arch::x86::_mm256_cvttpd_epi64;
713        #[cfg(target_arch = "x86_64")]
714        use core::arch::x86_64::_mm256_cvttpd_epi64;
715
716        // TODO(safe_arch): Add `_mm256_cvttpd_epi64`.
717        cast(m256i(unsafe { _mm256_cvttpd_epi64(self.avx.0) }))
718      } else {
719        let [a, b]: [f64x2; 2] = cast(self);
720        cast([a.fast_trunc_int(), b.fast_trunc_int()])
721      }
722    }
723  }
724
725  /// Truncates each lane into an integer. This saturates out of range values
726  /// and turns NaNs into 0. Use `fast_trunc_int` for a faster implementation
727  /// that doesn't handle out of range values or NaNs.
728  #[inline]
729  #[must_use]
730  pub fn trunc_int(self) -> i64x4 {
731    pick! {
732      if #[cfg(all(target_feature="avx512dq", target_feature="avx512vl"))] {
733        #[cfg(target_arch = "x86")]
734        use core::arch::x86::_mm256_cvttpd_epi64;
735        #[cfg(target_arch = "x86_64")]
736        use core::arch::x86_64::_mm256_cvttpd_epi64;
737
738        // Based on: https://github.com/v8/v8/blob/210987a552a2bf2a854b0baa9588a5959ff3979d/src/codegen/shared-ia32-x64/macro-assembler-shared-ia32-x64.h#L489-L504
739        let non_nan_mask = self.simd_eq(self);
740        let non_nan = self & non_nan_mask;
741        let flip_to_max: i64x4 = cast(self.simd_ge(Self::splat(9223372036854775808.0)));
742
743        // TODO(safe_arch): Add `_mm256_cvttpd_epi64`.
744        let cast: i64x4 = cast(m256i(unsafe { _mm256_cvttpd_epi64(non_nan.avx.0) }));
745        flip_to_max ^ cast
746      } else {
747        let [a, b]: [f64x2; 2] = cast(self);
748        cast([a.trunc_int(), b.trunc_int()])
749      }
750    }
751  }
752
753  #[inline]
754  #[must_use]
755  pub fn fract(self) -> Self {
756    self - self.trunc()
757  }
758
759  /// Performs a multiply-add operation: `self * m + a`
760  ///
761  /// When hardware FMA support is available, this computes the result with a
762  /// single rounding operation. Without FMA support, it falls back to separate
763  /// multiply and add operations with two roundings.
764  ///
765  /// # Platform-specific behavior
766  /// - On `x86`/`x86_64` with AVX+FMA: Uses 256-bit `vfmadd` (single rounding,
767  ///   best accuracy)
768  /// - On `x86`/`x86_64` with AVX only: Uses `(self * m) + a` (two roundings)
769  /// - Other platforms: Delegates to [`f64x2`] (may use NEON FMA or fallback)
770  ///
771  /// # Examples
772  /// ```
773  /// # use wide::f64x4;
774  /// let a = f64x4::from([1.0, 2.0, 3.0, 4.0]);
775  /// let b = f64x4::from([2.0; 4]);
776  /// let c = f64x4::from([10.0; 4]);
777  ///
778  /// let result = a.mul_add(b, c);
779  ///
780  /// let expected = f64x4::from([12.0, 14.0, 16.0, 18.0]);
781  /// assert_eq!(result, expected);
782  /// ```
783  #[inline]
784  #[must_use]
785  pub fn mul_add(self, m: Self, a: Self) -> Self {
786    pick! {
787      if #[cfg(all(target_feature="avx",target_feature="fma"))] {
788        Self { avx: fused_mul_add_m256d(self.avx, m.avx, a.avx) }
789      } else if #[cfg(target_feature="avx")] {
790        // still want to use 256 bit ops
791        (self * m) + a
792      } else {
793        Self {
794          a : self.a.mul_add(m.a, a.a),
795          b : self.b.mul_add(m.b, a.b),
796        }
797      }
798    }
799  }
800
801  /// Performs a multiply-subtract operation: `self * m - s`
802  ///
803  /// When hardware FMA support is available, this computes the result with a
804  /// single rounding operation. Without FMA support, it falls back to separate
805  /// multiply and subtract operations with two roundings.
806  ///
807  /// # Platform-specific behavior
808  /// - On `x86`/`x86_64` with AVX+FMA: Uses 256-bit `vfmsub` (single rounding,
809  ///   best accuracy)
810  /// - On `x86`/`x86_64` with AVX only: Uses `(self * m) - s` (two roundings)
811  /// - Other platforms: Delegates to [`f64x2`] (may use NEON FMA or fallback)
812  ///
813  /// # Examples
814  /// ```
815  /// # use wide::f64x4;
816  /// let a = f64x4::from([10.0; 4]);
817  /// let b = f64x4::from([2.0; 4]);
818  /// let c = f64x4::from([5.0; 4]);
819  ///
820  /// let result = a.mul_sub(b, c);
821  ///
822  /// let expected = f64x4::from([15.0; 4]);
823  /// assert_eq!(result, expected);
824  /// ```
825  #[inline]
826  #[must_use]
827  pub fn mul_sub(self, m: Self, s: Self) -> Self {
828    pick! {
829      if #[cfg(all(target_feature="avx",target_feature="fma"))] {
830        Self { avx: fused_mul_sub_m256d(self.avx, m.avx, s.avx) }
831      } else if #[cfg(target_feature="avx")] {
832        // still want to use 256 bit ops
833        (self * m) - s
834      } else {
835        Self {
836          a : self.a.mul_sub(m.a, s.a),
837          b : self.b.mul_sub(m.b, s.b),
838        }
839      }
840    }
841  }
842
843  /// Performs a negative multiply-add operation: `a - (self * m)`
844  ///
845  /// When hardware FMA support is available, this computes the result with a
846  /// single rounding operation. Without FMA support, it falls back to separate
847  /// operations with two roundings.
848  ///
849  /// # Platform-specific behavior
850  /// - On `x86`/`x86_64` with AVX+FMA: Uses 256-bit `vfnmadd` (single rounding,
851  ///   best accuracy)
852  /// - On `x86`/`x86_64` with AVX only: Uses `a - (self * m)` (two roundings)
853  /// - Other platforms: Delegates to [`f64x2`] (may use NEON FMA or fallback)
854  ///
855  /// # Examples
856  /// ```
857  /// # use wide::f64x4;
858  /// let a = f64x4::from([3.0; 4]);
859  /// let b = f64x4::from([2.0; 4]);
860  /// let c = f64x4::from([10.0; 4]);
861  ///
862  /// let result = a.mul_neg_add(b, c);
863  ///
864  /// let expected = f64x4::from([4.0; 4]);
865  /// assert_eq!(result, expected);
866  /// ```
867  #[inline]
868  #[must_use]
869  pub fn mul_neg_add(self, m: Self, a: Self) -> Self {
870    pick! {
871      if #[cfg(all(target_feature="avx",target_feature="fma"))] {
872        Self { avx: fused_mul_neg_add_m256d(self.avx, m.avx, a.avx) }
873      } else if #[cfg(target_feature="avx")] {
874        // still want to use 256 bit ops
875        a - (self * m)
876      } else {
877        Self {
878          a : self.a.mul_neg_add(m.a, a.a),
879          b : self.b.mul_neg_add(m.b, a.b),
880        }
881      }
882    }
883  }
884
885  /// Performs a negative multiply-subtract operation: `-(self * m) - s`
886  ///
887  /// When hardware FMA support is available, this computes the result with a
888  /// single rounding operation. Without FMA support, it falls back to separate
889  /// operations with two roundings.
890  ///
891  /// # Platform-specific behavior
892  /// - On `x86`/`x86_64` with AVX+FMA: Uses 256-bit `vfnmsub` (single rounding,
893  ///   best accuracy)
894  /// - On `x86`/`x86_64` with AVX only: Uses `-(self * m) - s` (two roundings)
895  /// - Other platforms: Delegates to [`f64x2`] (may use NEON FMA or fallback)
896  ///
897  /// # Examples
898  /// ```
899  /// # use wide::f64x4;
900  /// let a = f64x4::from([3.0; 4]);
901  /// let b = f64x4::from([2.0; 4]);
902  /// let c = f64x4::from([1.0; 4]);
903  ///
904  /// let result = a.mul_neg_sub(b, c);
905  ///
906  /// let expected = f64x4::from([-7.0; 4]);
907  /// assert_eq!(result, expected);
908  /// ```
909  #[inline]
910  #[must_use]
911  pub fn mul_neg_sub(self, m: Self, s: Self) -> Self {
912    pick! {
913       if #[cfg(all(target_feature="avx",target_feature="fma"))] {
914         Self { avx: fused_mul_neg_sub_m256d(self.avx, m.avx, s.avx) }
915        } else if #[cfg(target_feature="avx")] {
916          // still want to use 256 bit ops
917          -(self * m) - s
918        } else {
919         Self {
920           a : self.a.mul_neg_sub(m.a, s.a),
921           b : self.b.mul_neg_sub(m.b, s.b),
922         }
923       }
924    }
925  }
926
927  #[inline]
928  #[must_use]
929  pub fn div_euclid(self, rhs: Self) -> Self {
930    let q = (self / rhs).trunc();
931    (self % rhs)
932      .simd_lt(Self::ZERO)
933      .blend(rhs.simd_gt(Self::ZERO).blend(q - Self::ONE, q + Self::ONE), q)
934  }
935
936  #[inline]
937  #[must_use]
938  pub fn rem_euclid(self, rhs: Self) -> Self {
939    let r = self % rhs;
940    r.simd_lt(Self::ZERO).blend(r + rhs.abs(), r)
941  }
942
943  #[inline]
944  #[must_use]
945  pub fn flip_signs(self, signs: Self) -> Self {
946    self ^ (signs & Self::from(-0.0))
947  }
948
949  #[inline]
950  #[must_use]
951  pub fn copysign(self, sign: Self) -> Self {
952    let magnitude_mask = Self::from(f64::from_bits(u64::MAX >> 1));
953    (self & magnitude_mask) | (sign & Self::from(-0.0))
954  }
955
956  #[inline]
957  pub fn asin_acos(self) -> (Self, Self) {
958    // Based on the Agner Fog "vector class library":
959    // https://github.com/vectorclass/version2/blob/master/vectormath_trig.h
960    const_f64_as_f64x4!(R4asin, 2.967721961301243206100E-3);
961    const_f64_as_f64x4!(R3asin, -5.634242780008963776856E-1);
962    const_f64_as_f64x4!(R2asin, 6.968710824104713396794E0);
963    const_f64_as_f64x4!(R1asin, -2.556901049652824852289E1);
964    const_f64_as_f64x4!(R0asin, 2.853665548261061424989E1);
965
966    const_f64_as_f64x4!(S3asin, -2.194779531642920639778E1);
967    const_f64_as_f64x4!(S2asin, 1.470656354026814941758E2);
968    const_f64_as_f64x4!(S1asin, -3.838770957603691357202E2);
969    const_f64_as_f64x4!(S0asin, 3.424398657913078477438E2);
970
971    const_f64_as_f64x4!(P5asin, 4.253011369004428248960E-3);
972    const_f64_as_f64x4!(P4asin, -6.019598008014123785661E-1);
973    const_f64_as_f64x4!(P3asin, 5.444622390564711410273E0);
974    const_f64_as_f64x4!(P2asin, -1.626247967210700244449E1);
975    const_f64_as_f64x4!(P1asin, 1.956261983317594739197E1);
976    const_f64_as_f64x4!(P0asin, -8.198089802484824371615E0);
977
978    const_f64_as_f64x4!(Q4asin, -1.474091372988853791896E1);
979    const_f64_as_f64x4!(Q3asin, 7.049610280856842141659E1);
980    const_f64_as_f64x4!(Q2asin, -1.471791292232726029859E2);
981    const_f64_as_f64x4!(Q1asin, 1.395105614657485689735E2);
982    const_f64_as_f64x4!(Q0asin, -4.918853881490881290097E1);
983
984    let xa = self.abs();
985
986    let big = xa.simd_ge(f64x4::splat(0.625));
987
988    let x1 = big.blend(f64x4::splat(1.0) - xa, xa * xa);
989
990    let x2 = x1 * x1;
991    let x3 = x2 * x1;
992    let x4 = x2 * x2;
993    let x5 = x4 * x1;
994
995    let do_big = big.any();
996    let do_small = !big.all();
997
998    let mut rx = f64x4::default();
999    let mut sx = f64x4::default();
1000    let mut px = f64x4::default();
1001    let mut qx = f64x4::default();
1002
1003    if do_big {
1004      rx = x3.mul_add(R3asin, x2 * R2asin)
1005        + x4.mul_add(R4asin, x1.mul_add(R1asin, R0asin));
1006      sx =
1007        x3.mul_add(S3asin, x4) + x2.mul_add(S2asin, x1.mul_add(S1asin, S0asin));
1008    }
1009
1010    if do_small {
1011      px = x3.mul_add(P3asin, P0asin)
1012        + x4.mul_add(P4asin, x1 * P1asin)
1013        + x5.mul_add(P5asin, x2 * P2asin);
1014      qx = x4.mul_add(Q4asin, x5)
1015        + x3.mul_add(Q3asin, x1 * Q1asin)
1016        + x2.mul_add(Q2asin, Q0asin);
1017    };
1018
1019    let vx = big.blend(rx, px);
1020    let wx = big.blend(sx, qx);
1021
1022    let y1 = vx / wx * x1;
1023
1024    let mut z1 = f64x4::default();
1025    let mut z2 = f64x4::default();
1026    if do_big {
1027      let xb = (x1 + x1).sqrt();
1028      z1 = xb.mul_add(y1, xb);
1029    }
1030
1031    if do_small {
1032      z2 = xa.mul_add(y1, xa);
1033    }
1034
1035    // asin
1036    let z3 = f64x4::FRAC_PI_2 - z1;
1037    let asin = big.blend(z3, z2);
1038    let asin = asin.flip_signs(self);
1039
1040    // acos
1041    let z3 = self.simd_lt(f64x4::ZERO).blend(f64x4::PI - z1, z1);
1042    let z4 = f64x4::FRAC_PI_2 - z2.flip_signs(self);
1043    let acos = big.blend(z3, z4);
1044
1045    (asin, acos)
1046  }
1047
1048  #[inline]
1049  pub fn acos(self) -> Self {
1050    // Based on the Agner Fog "vector class library":
1051    // https://github.com/vectorclass/version2/blob/master/vectormath_trig.h
1052    const_f64_as_f64x4!(R4asin, 2.967721961301243206100E-3);
1053    const_f64_as_f64x4!(R3asin, -5.634242780008963776856E-1);
1054    const_f64_as_f64x4!(R2asin, 6.968710824104713396794E0);
1055    const_f64_as_f64x4!(R1asin, -2.556901049652824852289E1);
1056    const_f64_as_f64x4!(R0asin, 2.853665548261061424989E1);
1057
1058    const_f64_as_f64x4!(S3asin, -2.194779531642920639778E1);
1059    const_f64_as_f64x4!(S2asin, 1.470656354026814941758E2);
1060    const_f64_as_f64x4!(S1asin, -3.838770957603691357202E2);
1061    const_f64_as_f64x4!(S0asin, 3.424398657913078477438E2);
1062
1063    const_f64_as_f64x4!(P5asin, 4.253011369004428248960E-3);
1064    const_f64_as_f64x4!(P4asin, -6.019598008014123785661E-1);
1065    const_f64_as_f64x4!(P3asin, 5.444622390564711410273E0);
1066    const_f64_as_f64x4!(P2asin, -1.626247967210700244449E1);
1067    const_f64_as_f64x4!(P1asin, 1.956261983317594739197E1);
1068    const_f64_as_f64x4!(P0asin, -8.198089802484824371615E0);
1069
1070    const_f64_as_f64x4!(Q4asin, -1.474091372988853791896E1);
1071    const_f64_as_f64x4!(Q3asin, 7.049610280856842141659E1);
1072    const_f64_as_f64x4!(Q2asin, -1.471791292232726029859E2);
1073    const_f64_as_f64x4!(Q1asin, 1.395105614657485689735E2);
1074    const_f64_as_f64x4!(Q0asin, -4.918853881490881290097E1);
1075
1076    let xa = self.abs();
1077
1078    let big = xa.simd_ge(f64x4::splat(0.625));
1079
1080    let x1 = big.blend(f64x4::splat(1.0) - xa, xa * xa);
1081
1082    let x2 = x1 * x1;
1083    let x3 = x2 * x1;
1084    let x4 = x2 * x2;
1085    let x5 = x4 * x1;
1086
1087    let do_big = big.any();
1088    let do_small = !big.all();
1089
1090    let mut rx = f64x4::default();
1091    let mut sx = f64x4::default();
1092    let mut px = f64x4::default();
1093    let mut qx = f64x4::default();
1094
1095    if do_big {
1096      rx = x3.mul_add(R3asin, x2 * R2asin)
1097        + x4.mul_add(R4asin, x1.mul_add(R1asin, R0asin));
1098      sx =
1099        x3.mul_add(S3asin, x4) + x2.mul_add(S2asin, x1.mul_add(S1asin, S0asin));
1100    }
1101    if do_small {
1102      px = x3.mul_add(P3asin, P0asin)
1103        + x4.mul_add(P4asin, x1 * P1asin)
1104        + x5.mul_add(P5asin, x2 * P2asin);
1105      qx = x4.mul_add(Q4asin, x5)
1106        + x3.mul_add(Q3asin, x1 * Q1asin)
1107        + x2.mul_add(Q2asin, Q0asin);
1108    };
1109
1110    let vx = big.blend(rx, px);
1111    let wx = big.blend(sx, qx);
1112
1113    let y1 = vx / wx * x1;
1114
1115    let mut z1 = f64x4::default();
1116    let mut z2 = f64x4::default();
1117    if do_big {
1118      let xb = (x1 + x1).sqrt();
1119      z1 = xb.mul_add(y1, xb);
1120    }
1121
1122    if do_small {
1123      z2 = xa.mul_add(y1, xa);
1124    }
1125
1126    // acos
1127    let z3 = self.simd_lt(f64x4::ZERO).blend(f64x4::PI - z1, z1);
1128    let z4 = f64x4::FRAC_PI_2 - z2.flip_signs(self);
1129    let acos = big.blend(z3, z4);
1130
1131    acos
1132  }
1133  #[inline]
1134  #[must_use]
1135  pub fn asin(self) -> Self {
1136    // Based on the Agner Fog "vector class library":
1137    // https://github.com/vectorclass/version2/blob/master/vectormath_trig.h
1138    const_f64_as_f64x4!(R4asin, 2.967721961301243206100E-3);
1139    const_f64_as_f64x4!(R3asin, -5.634242780008963776856E-1);
1140    const_f64_as_f64x4!(R2asin, 6.968710824104713396794E0);
1141    const_f64_as_f64x4!(R1asin, -2.556901049652824852289E1);
1142    const_f64_as_f64x4!(R0asin, 2.853665548261061424989E1);
1143
1144    const_f64_as_f64x4!(S3asin, -2.194779531642920639778E1);
1145    const_f64_as_f64x4!(S2asin, 1.470656354026814941758E2);
1146    const_f64_as_f64x4!(S1asin, -3.838770957603691357202E2);
1147    const_f64_as_f64x4!(S0asin, 3.424398657913078477438E2);
1148
1149    const_f64_as_f64x4!(P5asin, 4.253011369004428248960E-3);
1150    const_f64_as_f64x4!(P4asin, -6.019598008014123785661E-1);
1151    const_f64_as_f64x4!(P3asin, 5.444622390564711410273E0);
1152    const_f64_as_f64x4!(P2asin, -1.626247967210700244449E1);
1153    const_f64_as_f64x4!(P1asin, 1.956261983317594739197E1);
1154    const_f64_as_f64x4!(P0asin, -8.198089802484824371615E0);
1155
1156    const_f64_as_f64x4!(Q4asin, -1.474091372988853791896E1);
1157    const_f64_as_f64x4!(Q3asin, 7.049610280856842141659E1);
1158    const_f64_as_f64x4!(Q2asin, -1.471791292232726029859E2);
1159    const_f64_as_f64x4!(Q1asin, 1.395105614657485689735E2);
1160    const_f64_as_f64x4!(Q0asin, -4.918853881490881290097E1);
1161
1162    let xa = self.abs();
1163
1164    let big = xa.simd_ge(f64x4::splat(0.625));
1165
1166    let x1 = big.blend(f64x4::splat(1.0) - xa, xa * xa);
1167
1168    let x2 = x1 * x1;
1169    let x3 = x2 * x1;
1170    let x4 = x2 * x2;
1171    let x5 = x4 * x1;
1172
1173    let do_big = big.any();
1174    let do_small = !big.all();
1175
1176    let mut rx = f64x4::default();
1177    let mut sx = f64x4::default();
1178    let mut px = f64x4::default();
1179    let mut qx = f64x4::default();
1180
1181    if do_big {
1182      rx = x3.mul_add(R3asin, x2 * R2asin)
1183        + x4.mul_add(R4asin, x1.mul_add(R1asin, R0asin));
1184      sx =
1185        x3.mul_add(S3asin, x4) + x2.mul_add(S2asin, x1.mul_add(S1asin, S0asin));
1186    }
1187    if do_small {
1188      px = x3.mul_add(P3asin, P0asin)
1189        + x4.mul_add(P4asin, x1 * P1asin)
1190        + x5.mul_add(P5asin, x2 * P2asin);
1191      qx = x4.mul_add(Q4asin, x5)
1192        + x3.mul_add(Q3asin, x1 * Q1asin)
1193        + x2.mul_add(Q2asin, Q0asin);
1194    };
1195
1196    let vx = big.blend(rx, px);
1197    let wx = big.blend(sx, qx);
1198
1199    let y1 = vx / wx * x1;
1200
1201    let mut z1 = f64x4::default();
1202    let mut z2 = f64x4::default();
1203    if do_big {
1204      let xb = (x1 + x1).sqrt();
1205      z1 = xb.mul_add(y1, xb);
1206    }
1207
1208    if do_small {
1209      z2 = xa.mul_add(y1, xa);
1210    }
1211
1212    // asin
1213    let z3 = f64x4::FRAC_PI_2 - z1;
1214    let asin = big.blend(z3, z2);
1215    let asin = asin.flip_signs(self);
1216
1217    asin
1218  }
1219
1220  #[inline]
1221  pub fn atan(self) -> Self {
1222    // Based on the Agner Fog "vector class library":
1223    // https://github.com/vectorclass/version2/blob/master/vectormath_trig.h
1224    const_f64_as_f64x4!(MORE_BITS, 6.123233995736765886130E-17);
1225    const_f64_as_f64x4!(MORE_BITS_O2, 6.123233995736765886130E-17 * 0.5);
1226    const_f64_as_f64x4!(T3PO8, core::f64::consts::SQRT_2 + 1.0);
1227
1228    const_f64_as_f64x4!(P4atan, -8.750608600031904122785E-1);
1229    const_f64_as_f64x4!(P3atan, -1.615753718733365076637E1);
1230    const_f64_as_f64x4!(P2atan, -7.500855792314704667340E1);
1231    const_f64_as_f64x4!(P1atan, -1.228866684490136173410E2);
1232    const_f64_as_f64x4!(P0atan, -6.485021904942025371773E1);
1233
1234    const_f64_as_f64x4!(Q4atan, 2.485846490142306297962E1);
1235    const_f64_as_f64x4!(Q3atan, 1.650270098316988542046E2);
1236    const_f64_as_f64x4!(Q2atan, 4.328810604912902668951E2);
1237    const_f64_as_f64x4!(Q1atan, 4.853903996359136964868E2);
1238    const_f64_as_f64x4!(Q0atan, 1.945506571482613964425E2);
1239
1240    let t = self.abs();
1241
1242    // small:  t < 0.66
1243    // medium: t <= t <= 2.4142 (1+sqrt(2))
1244    // big:    t > 2.4142
1245    let notbig = t.simd_le(T3PO8);
1246    let notsmal = t.simd_ge(Self::splat(0.66));
1247
1248    let mut s = notbig.blend(Self::FRAC_PI_4, Self::FRAC_PI_2);
1249    s = notsmal & s;
1250    let mut fac = notbig.blend(MORE_BITS_O2, MORE_BITS);
1251    fac = notsmal & fac;
1252
1253    // small:  z = t / 1.0;
1254    // medium: z = (t-1.0) / (t+1.0);
1255    // big:    z = -1.0 / t;
1256    let mut a = notbig & t;
1257    a = notsmal.blend(a - Self::ONE, a);
1258    let mut b = notbig & Self::ONE;
1259    b = notsmal.blend(b + t, b);
1260    let z = a / b;
1261
1262    let zz = z * z;
1263
1264    let px = polynomial_4!(zz, P0atan, P1atan, P2atan, P3atan, P4atan);
1265    let qx = polynomial_5n!(zz, Q0atan, Q1atan, Q2atan, Q3atan, Q4atan);
1266
1267    let mut re = (px / qx).mul_add(z * zz, z);
1268    re += s + fac;
1269
1270    // get sign bit
1271    re = (self.is_sign_negative()).blend(-re, re);
1272
1273    re
1274  }
1275
1276  #[inline]
1277  pub fn atan2(self, x: Self) -> Self {
1278    // Based on the Agner Fog "vector class library":
1279    // https://github.com/vectorclass/version2/blob/master/vectormath_trig.h
1280    const_f64_as_f64x4!(MORE_BITS, 6.123233995736765886130E-17);
1281    const_f64_as_f64x4!(MORE_BITS_O2, 6.123233995736765886130E-17 * 0.5);
1282    const_f64_as_f64x4!(T3PO8, core::f64::consts::SQRT_2 + 1.0);
1283
1284    const_f64_as_f64x4!(P4atan, -8.750608600031904122785E-1);
1285    const_f64_as_f64x4!(P3atan, -1.615753718733365076637E1);
1286    const_f64_as_f64x4!(P2atan, -7.500855792314704667340E1);
1287    const_f64_as_f64x4!(P1atan, -1.228866684490136173410E2);
1288    const_f64_as_f64x4!(P0atan, -6.485021904942025371773E1);
1289
1290    const_f64_as_f64x4!(Q4atan, 2.485846490142306297962E1);
1291    const_f64_as_f64x4!(Q3atan, 1.650270098316988542046E2);
1292    const_f64_as_f64x4!(Q2atan, 4.328810604912902668951E2);
1293    const_f64_as_f64x4!(Q1atan, 4.853903996359136964868E2);
1294    const_f64_as_f64x4!(Q0atan, 1.945506571482613964425E2);
1295
1296    let y = self;
1297
1298    // move in first octant
1299    let x1 = x.abs();
1300    let y1 = y.abs();
1301    let swapxy = y1.simd_gt(x1);
1302    // swap x and y if y1 > x1
1303    let mut x2 = swapxy.blend(y1, x1);
1304    let mut y2 = swapxy.blend(x1, y1);
1305
1306    // check for special case: x and y are both +/- INF
1307    let both_infinite = x.is_inf() & y.is_inf();
1308    if both_infinite.any() {
1309      let minus_one = -Self::ONE;
1310      x2 = both_infinite.blend(x2 & minus_one, x2);
1311      y2 = both_infinite.blend(y2 & minus_one, y2);
1312    }
1313
1314    // x = y = 0 gives NAN here
1315    let t = y2 / x2;
1316
1317    // small:  t < 0.66
1318    // medium: t <= t <= 2.4142 (1+sqrt(2))
1319    // big:    t > 2.4142
1320    let notbig = t.simd_le(T3PO8);
1321    let notsmal = t.simd_ge(Self::splat(0.66));
1322
1323    let mut s = notbig.blend(Self::FRAC_PI_4, Self::FRAC_PI_2);
1324    s = notsmal & s;
1325    let mut fac = notbig.blend(MORE_BITS_O2, MORE_BITS);
1326    fac = notsmal & fac;
1327
1328    // small:  z = t / 1.0;
1329    // medium: z = (t-1.0) / (t+1.0);
1330    // big:    z = -1.0 / t;
1331    let mut a = notbig & t;
1332    a = notsmal.blend(a - Self::ONE, a);
1333    let mut b = notbig & Self::ONE;
1334    b = notsmal.blend(b + t, b);
1335    let z = a / b;
1336
1337    let zz = z * z;
1338
1339    let px = polynomial_4!(zz, P0atan, P1atan, P2atan, P3atan, P4atan);
1340    let qx = polynomial_5n!(zz, Q0atan, Q1atan, Q2atan, Q3atan, Q4atan);
1341
1342    let mut re = (px / qx).mul_add(z * zz, z);
1343    re += s + fac;
1344
1345    // move back in place
1346    re = swapxy.blend(Self::FRAC_PI_2 - re, re);
1347    re = ((x | y).simd_eq(Self::ZERO)).blend(Self::ZERO, re);
1348    re = (x.is_sign_negative()).blend(Self::PI - re, re);
1349
1350    // get sign bit
1351    re = (y.is_sign_negative()).blend(-re, re);
1352
1353    re
1354  }
1355
1356  #[inline]
1357  #[must_use]
1358  pub fn sin_cos(self) -> (Self, Self) {
1359    // Based on the Agner Fog "vector class library":
1360    // https://github.com/vectorclass/version2/blob/master/vectormath_trig.h
1361
1362    const_f64_as_f64x4!(P0sin, -1.66666666666666307295E-1);
1363    const_f64_as_f64x4!(P1sin, 8.33333333332211858878E-3);
1364    const_f64_as_f64x4!(P2sin, -1.98412698295895385996E-4);
1365    const_f64_as_f64x4!(P3sin, 2.75573136213857245213E-6);
1366    const_f64_as_f64x4!(P4sin, -2.50507477628578072866E-8);
1367    const_f64_as_f64x4!(P5sin, 1.58962301576546568060E-10);
1368
1369    const_f64_as_f64x4!(P0cos, 4.16666666666665929218E-2);
1370    const_f64_as_f64x4!(P1cos, -1.38888888888730564116E-3);
1371    const_f64_as_f64x4!(P2cos, 2.48015872888517045348E-5);
1372    const_f64_as_f64x4!(P3cos, -2.75573141792967388112E-7);
1373    const_f64_as_f64x4!(P4cos, 2.08757008419747316778E-9);
1374    const_f64_as_f64x4!(P5cos, -1.13585365213876817300E-11);
1375
1376    const_f64_as_f64x4!(DP1, 7.853981554508209228515625E-1 * 2.);
1377    const_f64_as_f64x4!(DP2, 7.94662735614792836714E-9 * 2.);
1378    const_f64_as_f64x4!(DP3, 3.06161699786838294307E-17 * 2.);
1379
1380    const_f64_as_f64x4!(TWO_OVER_PI, 2.0 / core::f64::consts::PI);
1381
1382    let xa = self.abs();
1383
1384    let y = (xa * TWO_OVER_PI).round();
1385    let q = y.round_int();
1386
1387    let x = y.mul_neg_add(DP3, y.mul_neg_add(DP2, y.mul_neg_add(DP1, xa)));
1388
1389    let x2 = x * x;
1390    let mut s = polynomial_5!(x2, P0sin, P1sin, P2sin, P3sin, P4sin, P5sin);
1391    let mut c = polynomial_5!(x2, P0cos, P1cos, P2cos, P3cos, P4cos, P5cos);
1392    s = (x * x2).mul_add(s, x);
1393    c =
1394      (x2 * x2).mul_add(c, x2.mul_neg_add(f64x4::from(0.5), f64x4::from(1.0)));
1395
1396    let swap = !((q & i64x4::from(1)).simd_eq(i64x4::from(0)));
1397
1398    let mut overflow: f64x4 = cast(q.simd_gt(i64x4::from(0x80000000000000)));
1399    overflow &= xa.is_finite();
1400    s = overflow.blend(f64x4::from(0.0), s);
1401    c = overflow.blend(f64x4::from(1.0), c);
1402
1403    // calc sin
1404    let mut sin1 = cast::<_, f64x4>(swap).blend(c, s);
1405    let sign_sin: i64x4 = (q << 62) ^ cast::<_, i64x4>(self);
1406    sin1 = sin1.flip_signs(cast(sign_sin));
1407
1408    // calc cos
1409    let mut cos1 = cast::<_, f64x4>(swap).blend(s, c);
1410    let sign_cos: i64x4 = ((q + i64x4::from(1)) & i64x4::from(2)) << 62;
1411    cos1 ^= cast::<_, f64x4>(sign_cos);
1412
1413    // IEEE 754: sin/cos(±∞) = NaN, sin/cos(NaN) = NaN
1414    let finite = self.is_finite();
1415    let nan = Self::splat(f64::NAN);
1416    let sin_final = finite.blend(sin1, nan);
1417    let cos_final = finite.blend(cos1, nan);
1418
1419    (sin_final, cos_final)
1420  }
1421  #[inline]
1422  #[must_use]
1423  pub fn sin(self) -> Self {
1424    let (s, _) = self.sin_cos();
1425    s
1426  }
1427  #[inline]
1428  #[must_use]
1429  pub fn cos(self) -> Self {
1430    let (_, c) = self.sin_cos();
1431    c
1432  }
1433  #[inline]
1434  #[must_use]
1435  pub fn tan(self) -> Self {
1436    let (s, c) = self.sin_cos();
1437    s / c
1438  }
1439
1440  /// Calculates hyperbolic sine: `(e^self - e^(-self))/2`.
1441  #[inline]
1442  #[must_use]
1443  pub fn sinh(self) -> Self {
1444    const_f64_as_f64x4!(P0, 1.0);
1445    const_f64_as_f64x4!(P1, 1.0 / 6.0);
1446    const_f64_as_f64x4!(P2, 1.0 / 120.0);
1447    const_f64_as_f64x4!(P3, 1.0 / 5040.0);
1448    const_f64_as_f64x4!(P4, 1.0 / 362880.0);
1449    const_f64_as_f64x4!(P5, 1.0 / 39916800.0);
1450    const_f64_as_f64x4!(P6, 1.0 / 6227020800.0);
1451    let a = self.abs();
1452    // |x| < 0.5: Taylor poly; last truncation term < 1 ULP at x=0.5 for both types
1453    let small = a.simd_lt(f64x4::from(0.5));
1454    let t = a * a;
1455    let poly = a * polynomial_6!(t, P0, P1, P2, P3, P4, P5, P6);
1456    let exp_based = {
1457      let e = a.exp();
1458      (e - Self::ONE / e) * Self::HALF
1459    };
1460    let result = small.blend(poly, exp_based);
1461    result.flip_signs(self)
1462  }
1463
1464  /// Calculates hyperbolic cosine: `(e^self + e^(-self))/2`.
1465  #[inline]
1466  #[must_use]
1467  pub fn cosh(self) -> Self {
1468    const_f64_as_f64x4!(P0, 1.0);
1469    const_f64_as_f64x4!(P1, 1.0 / 2.0);
1470    const_f64_as_f64x4!(P2, 1.0 / 24.0);
1471    const_f64_as_f64x4!(P3, 1.0 / 720.0);
1472    const_f64_as_f64x4!(P4, 1.0 / 40320.0);
1473    const_f64_as_f64x4!(P5, 1.0 / 3628800.0);
1474    const_f64_as_f64x4!(P6, 1.0 / 479001600.0);
1475    const_f64_as_f64x4!(P7, 1.0 / 87178291200.0);
1476    let a = self.abs();
1477    // |x| < 0.5: Taylor poly; last truncation term < 1 ULP at x=0.5 for both types
1478    let small = a.simd_lt(f64x4::from(0.5));
1479    let t = a * a;
1480    let poly = polynomial_7!(t, P0, P1, P2, P3, P4, P5, P6, P7);
1481    let exp_based = {
1482      let e = a.exp();
1483      (e + Self::ONE / e) * Self::HALF
1484    };
1485    small.blend(poly, exp_based)
1486  }
1487
1488  /// Calculates hyperbolic tangent: `sinh(self)/cosh(self)`.
1489  #[inline]
1490  #[must_use]
1491  pub fn tanh(self) -> Self {
1492    // |x| < 5e-8: tanh(x) ≈ x, error x³/3 < 16·ULP(x)
1493    // bound: x² < 48·2⁻⁵² → x < 1.03e-7; 5e-8 has 2× margin
1494    // |x| > 19.062: tanh(x) = ±1 to f64 precision (e⁻²ˣ < 2⁻⁵⁴)
1495    let a = self.abs();
1496    let large = a.simd_gt(f64x4::from(19.062));
1497    if large.all() {
1498      return Self::ONE.flip_signs(self);
1499    }
1500    let small = a.simd_lt(f64x4::from(5e-8));
1501    let exp_based = {
1502      let t = (Self::from(-2.0) * a).exp_m1();
1503      let pos = -t / (t + Self::from(2.0));
1504      pos.flip_signs(self)
1505    };
1506    let result = small.blend(self, exp_based);
1507    large.blend(Self::ONE.flip_signs(self), result)
1508  }
1509
1510  /// Calculates the cube root: `self^(1/3)`.
1511  #[inline]
1512  #[must_use]
1513  pub fn cbrt(self) -> Self {
1514    let a = self.abs();
1515    let zero = a.simd_eq(Self::ZERO);
1516    if zero.all() {
1517      return self; // preserves -0.0
1518    }
1519    let inf = a.is_inf();
1520    let nan = self.is_nan();
1521
1522    const SUBN_SCALE: f64 = 1.8014398509481984e16;
1523    const SUBN_CBRT: f64 = 262144.0;
1524    let tiny = a.simd_lt(Self::from(f64::MIN_POSITIVE));
1525    let a = tiny.blend(a * Self::from(SUBN_SCALE), a);
1526
1527    let e = Self::exponent(a) + Self::ONE;
1528    let d = Self::fraction_2(a);
1529
1530    // C0..C5 from SLEEF's minimax polynomial for 1/cbrt(d) on [0.5, 1.0)
1531    // Naoki Shibata et al., "SLEEF: A Portable Vectorized Library of C99
1532    // Mathematical Functions", https://sleef.org / https://github.com/shibatch/sleef
1533    // Licensed under the Boost Software License 1.0.
1534    const_f64_as_f64x4!(C0, 2.2307275302496609725722);
1535    const_f64_as_f64x4!(C1, -3.85841935510444988821632);
1536    const_f64_as_f64x4!(C2, 6.03990368989458747961407);
1537    const_f64_as_f64x4!(C3, -5.73353060922947843636166);
1538    const_f64_as_f64x4!(C4, 2.96155103020039511818595);
1539    const_f64_as_f64x4!(C5, -0.640245898480692909870982);
1540    let mut x = polynomial_5!(d, C0, C1, C2, C3, C4, C5);
1541
1542    // Newton for 1/cbrt: x = x - (d * x^4 - x) / 3.
1543    let x2 = x * x;
1544    let x4 = x2 * x2;
1545    x = x - d.mul_add(x4, -x) * Self::from(1.0 / 3.0);
1546
1547    // cbrt(d) = d * x^2, then polish
1548    let mut y = (d * x) * x;
1549    let yx = y * x;
1550    let t = Self::from(2.0 / 3.0);
1551    y = y - t * y * (yx - Self::ONE);
1552
1553    // Scale by 2^(e/3) = 2^k * 2^(r/3)
1554    let three = Self::from(3.0);
1555    let two = Self::from(2.0);
1556    let neg = e.simd_lt(Self::ZERO);
1557    let e_adj = neg.blend(e - two, e);
1558    let k = (e_adj / three).trunc();
1559    let r = e - three * k;
1560    const_f64_as_f64x4!(CBRT2, 1.2599210498948732);
1561    const_f64_as_f64x4!(CBRT4, 1.5874010519681994);
1562    y = r.simd_eq(Self::ONE).blend(y * CBRT2, y);
1563    y = r.simd_eq(two).blend(y * CBRT4, y);
1564    y *= Self::vm_pow2n(k);
1565    y = tiny.blend(y / Self::from(SUBN_CBRT), y);
1566
1567    let result = y.flip_signs(self);
1568    let result = nan.blend(self, result);
1569    let result = zero.blend(self, result);
1570    let result = inf.blend(self, result);
1571    result
1572  }
1573
1574  #[inline]
1575  #[must_use]
1576  pub fn to_degrees(self) -> Self {
1577    const_f64_as_f64x4!(RAD_TO_DEG_RATIO, 180.0_f64 / core::f64::consts::PI);
1578    self * RAD_TO_DEG_RATIO
1579  }
1580  #[inline]
1581  #[must_use]
1582  pub fn to_radians(self) -> Self {
1583    const_f64_as_f64x4!(DEG_TO_RAD_RATIO, core::f64::consts::PI / 180.0_f64);
1584    self * DEG_TO_RAD_RATIO
1585  }
1586
1587  #[inline]
1588  #[must_use]
1589  pub fn recip(self) -> Self {
1590    // There does not seem to be a `recip` intrinsic for any architecture. The
1591    // closest is `_mm256_rcp14_pd` which has relative error.
1592    Self::ONE / self
1593  }
1594
1595  #[inline]
1596  #[must_use]
1597  pub fn recip_sqrt(self) -> Self {
1598    // There does not seem to be a `recip_sqrt` intrinsic for any architecture.
1599    // The closest is `_mm256_rsqrt14_pd` which has relative error.
1600    Self::ONE / self.sqrt()
1601  }
1602
1603  #[inline]
1604  #[must_use]
1605  pub fn sqrt(self) -> Self {
1606    pick! {
1607      if #[cfg(target_feature="avx")] {
1608        Self { avx: sqrt_m256d(self.avx) }
1609      } else {
1610        Self {
1611          a : self.a.sqrt(),
1612          b : self.b.sqrt(),
1613        }
1614      }
1615    }
1616  }
1617  #[inline]
1618  #[must_use]
1619  #[doc(alias("movemask", "move_mask"))]
1620  pub fn to_bitmask(self) -> u32 {
1621    pick! {
1622      if #[cfg(target_feature="avx")] {
1623        move_mask_m256d(self.avx) as u32
1624      } else {
1625        (self.b.to_bitmask() << 2) | self.a.to_bitmask()
1626      }
1627    }
1628  }
1629  #[inline]
1630  #[must_use]
1631  pub fn any(self) -> bool {
1632    pick! {
1633      if #[cfg(target_feature="avx")] {
1634        move_mask_m256d(self.avx) != 0
1635      } else {
1636        self.a.any() || self.b.any()
1637      }
1638    }
1639  }
1640  #[inline]
1641  #[must_use]
1642  pub fn all(self) -> bool {
1643    pick! {
1644      if #[cfg(target_feature="avx")] {
1645        move_mask_m256d(self.avx) == 0b1111
1646      } else {
1647        self.a.all() && self.b.all()
1648      }
1649    }
1650  }
1651  #[inline]
1652  #[must_use]
1653  pub fn none(self) -> bool {
1654    !self.any()
1655  }
1656
1657  #[inline]
1658  fn vm_pow2n(self) -> Self {
1659    const_f64_as_f64x4!(pow2_52, 4503599627370496.0);
1660    const_f64_as_f64x4!(bias, 1023.0);
1661    let a = self + (bias + pow2_52);
1662    let c = cast::<_, i64x4>(a) << 52;
1663    let std_result = cast::<_, f64x4>(c);
1664
1665    let min_exp = f64x4::from(-1022.0);
1666    let is_sub = self.simd_lt(min_exp);
1667    if is_sub.any() {
1668      let valid = self.simd_ge(f64x4::from(-1074.0));
1669      let shift_f = self + f64x4::from(1074.0);
1670      let mut shift_i = shift_f.trunc_int();
1671      shift_i = cast::<_, i64x4>(valid).blend(shift_i, i64x4::ZERO);
1672      let mantissa = i64x4::ONE << shift_i;
1673      let sub_result = cast::<_, f64x4>(mantissa);
1674      let sub_result = valid.blend(sub_result, f64x4::ZERO);
1675      is_sub.blend(sub_result, std_result)
1676    } else {
1677      std_result
1678    }
1679  }
1680
1681  /// Calculate the exponent of a packed `f64x4`
1682  #[inline]
1683  #[must_use]
1684  pub fn exp(self) -> Self {
1685    const_f64_as_f64x4!(P2, 1.0 / 2.0);
1686    const_f64_as_f64x4!(P3, 1.0 / 6.0);
1687    const_f64_as_f64x4!(P4, 1.0 / 24.0);
1688    const_f64_as_f64x4!(P5, 1.0 / 120.0);
1689    const_f64_as_f64x4!(P6, 1.0 / 720.0);
1690    const_f64_as_f64x4!(P7, 1.0 / 5040.0);
1691    const_f64_as_f64x4!(P8, 1.0 / 40320.0);
1692    const_f64_as_f64x4!(P9, 1.0 / 362880.0);
1693    const_f64_as_f64x4!(P10, 1.0 / 3628800.0);
1694    const_f64_as_f64x4!(P11, 1.0 / 39916800.0);
1695    const_f64_as_f64x4!(P12, 1.0 / 479001600.0);
1696    const_f64_as_f64x4!(P13, 1.0 / 6227020800.0);
1697    // LN2D_HI/LO: double-double decomposition of ln(2) for exp range reduction,
1698    // following fdlibm's approach (Sun Microsystems, https://www.netlib.org/fdlibm/ e_exp.c).
1699    // Values chosen so LN2D_HI + LN2D_LO = ln(2) to full f64 precision.
1700    const_f64_as_f64x4!(LN2D_HI, 0.693145751953125);
1701    const_f64_as_f64x4!(LN2D_LO, 1.42860682030941723212E-6);
1702    let max_x = f64x4::from(709.783);
1703    let min_x = f64x4::from(-744.79);
1704    let finite = self.is_finite();
1705    // x < min_x: e^x underflows to 0 -- skip the entire pipeline
1706    let neg_underflow = self.simd_lt(min_x) & finite;
1707    if neg_underflow.all() {
1708      return Self::ZERO;
1709    }
1710    let max_r = f64x4::from(1023.0);
1711    let r = (self * Self::LOG2_E).round();
1712    let big = r.simd_gt(max_r);
1713    let r_safe = big.blend(max_r, r);
1714    let excess = r - max_r;
1715    let excess = big.blend(excess, Self::ZERO);
1716    let scale = Self::vm_pow2n(excess);
1717    let x = r.mul_neg_add(LN2D_HI, self);
1718    let x = r.mul_neg_add(LN2D_LO, x);
1719    let z =
1720      polynomial_13!(x, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13);
1721    let n2 = Self::vm_pow2n(r_safe);
1722    let z = (z + Self::ONE) * scale * n2;
1723    let nan_mask = self.is_nan();
1724    let mut result = nan_mask.blend(Self::nan_pow(), z);
1725    let pos_overflow = self.simd_gt(max_x) & finite;
1726    result = pos_overflow.blend(Self::infinity(), result);
1727    result = neg_underflow.blend(Self::ZERO, result);
1728    let pos_inf = !finite & !self.is_sign_negative() & !nan_mask;
1729    result = pos_inf.blend(Self::infinity(), result);
1730    let neg_inf = !finite & self.is_sign_negative() & !nan_mask;
1731    result = neg_inf.blend(Self::ZERO, result);
1732    result
1733  }
1734
1735  /// Calculate `e^self - 1` for each lane.
1736  /// Accurate even for very small values.
1737  #[inline]
1738  #[must_use]
1739  pub fn exp_m1(self) -> Self {
1740    const_f64_as_f64x4!(P2, 1.0 / 2.0);
1741    const_f64_as_f64x4!(P3, 1.0 / 6.0);
1742    const_f64_as_f64x4!(P4, 1.0 / 24.0);
1743    const_f64_as_f64x4!(P5, 1.0 / 120.0);
1744    const_f64_as_f64x4!(P6, 1.0 / 720.0);
1745    const_f64_as_f64x4!(P7, 1.0 / 5040.0);
1746    const_f64_as_f64x4!(P8, 1.0 / 40320.0);
1747    const_f64_as_f64x4!(P9, 1.0 / 362880.0);
1748    const_f64_as_f64x4!(P10, 1.0 / 3628800.0);
1749    const_f64_as_f64x4!(P11, 1.0 / 39916800.0);
1750    const_f64_as_f64x4!(P12, 1.0 / 479001600.0);
1751    const_f64_as_f64x4!(P13, 1.0 / 6227020800.0);
1752    // LN2D_HI/LO: double-double decomposition of ln(2) for exp range reduction,
1753    // following fdlibm's approach (Sun Microsystems, https://www.netlib.org/fdlibm/ e_exp.c).
1754    const_f64_as_f64x4!(LN2D_HI, 0.693145751953125);
1755    const_f64_as_f64x4!(LN2D_LO, 1.42860682030941723212E-6);
1756    // x < -37.429: e^x < 2⁻⁵⁴, exp_m1(x) = -1.0 exactly (mantissa exhaustion)
1757    // IEEE simd_lt returns false for NaN, so NaN lanes can't reach here.
1758    // -inf is < -37.429, and exp_m1(-inf) = -1.0, also correct.
1759    if self.simd_lt(f64x4::from(-37.429)).all() {
1760      return f64x4::from(-1.0);
1761    }
1762    // max_x = ln(f64::MAX) ≈ 709.7827129, max_r = 1023 (IEEE max normal
1763    // exponent) min_x = -1074.5 ln(2) ≈ -744.79: min r for vm_pow2n to
1764    // construct subnormal
1765    let max_x = f64x4::from(709.783);
1766    let min_x = f64x4::from(-744.79);
1767    let max_r = f64x4::from(1023.0);
1768    let r = (self * Self::LOG2_E).round();
1769    let big = r.simd_gt(max_r);
1770    let r_safe = big.blend(max_r, r);
1771    let excess = r - max_r;
1772    let excess = big.blend(excess, Self::ZERO);
1773    let scale = Self::vm_pow2n(excess);
1774    let x = r.mul_neg_add(LN2D_HI, self);
1775    let x = r.mul_neg_add(LN2D_LO, x);
1776    let z =
1777      polynomial_13!(x, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13);
1778    let n2 = Self::vm_pow2n(r_safe);
1779    let exp_val = (z + Self::ONE) * scale * n2;
1780    // When r == 0, z is already e^x - 1 from the Taylor poly.
1781    // Computing (z+1) - 1 would lose low bits for small x (catastrophic
1782    // cancellation at z ~ 0), so keep z directly.
1783    let r_is_zero = r.simd_eq(Self::ZERO);
1784    let z = r_is_zero.blend(z, exp_val - Self::ONE);
1785    let nan_mask = self.is_nan();
1786    let finite = self.is_finite();
1787    let mut result = nan_mask.blend(Self::nan_pow(), z);
1788    let pos_overflow = self.simd_gt(max_x) & finite;
1789    result = pos_overflow.blend(Self::infinity(), result);
1790    let neg_underflow = self.simd_lt(min_x) & finite;
1791    result = neg_underflow.blend(-Self::ONE, result);
1792    let pos_inf = !finite & !self.is_sign_negative() & !nan_mask;
1793    result = pos_inf.blend(Self::infinity(), result);
1794    let neg_inf = !finite & self.is_sign_negative() & !nan_mask;
1795    result = neg_inf.blend(-Self::ONE, result);
1796    let is_zero = self.simd_eq(Self::ZERO);
1797    result = is_zero.blend(self, result);
1798    result
1799  }
1800
1801  /// Returns `2^self`.
1802  #[inline]
1803  #[must_use]
1804  pub fn exp2(self) -> Self {
1805    const_f64_as_f64x4!(P2, 1.0 / 2.0);
1806    const_f64_as_f64x4!(P3, 1.0 / 6.0);
1807    const_f64_as_f64x4!(P4, 1.0 / 24.0);
1808    const_f64_as_f64x4!(P5, 1.0 / 120.0);
1809    const_f64_as_f64x4!(P6, 1.0 / 720.0);
1810    const_f64_as_f64x4!(P7, 1.0 / 5040.0);
1811    const_f64_as_f64x4!(P8, 1.0 / 40320.0);
1812    const_f64_as_f64x4!(P9, 1.0 / 362880.0);
1813    const_f64_as_f64x4!(P10, 1.0 / 3628800.0);
1814
1815    // max_x = log2(f64::MAX) ≈ 1023.9999999999999
1816    // min_x = log2(f64::MIN_POSITIVE) - 52 ≈ -1022 - 52 = -1074
1817    let max_x = f64x4::from(1023.9999999999999);
1818    let min_x = f64x4::from(-1074.5);
1819    let finite = self.is_finite();
1820    let neg_underflow = self.simd_lt(min_x) & finite;
1821    if neg_underflow.all() {
1822      return Self::ZERO;
1823    }
1824
1825    let round = self.round();
1826    let max_r = f64x4::from(1023.0);
1827    let big = round.simd_gt(max_r);
1828    let r_safe = big.blend(max_r, round);
1829    let excess = round - max_r;
1830    let excess = big.blend(excess, Self::ZERO);
1831    let scale = Self::vm_pow2n(excess);
1832
1833    let fract = (self - round) * Self::LN_2;
1834    let fract_partial_exp2 =
1835      polynomial_8!(fract, P2, P3, P4, P5, P6, P7, P8, P9, P10);
1836    let fract2 = fract * fract;
1837    let fract_exp2 = fract_partial_exp2.mul_add(fract2, fract) + Self::ONE;
1838
1839    let n2 = Self::vm_pow2n(r_safe);
1840    let result = fract_exp2 * scale * n2;
1841
1842    let nan_mask = self.is_nan();
1843    let mut result = nan_mask.blend(Self::nan_pow(), result);
1844    let pos_overflow = self.simd_gt(max_x) & finite;
1845    result = pos_overflow.blend(Self::infinity(), result);
1846    result = neg_underflow.blend(Self::ZERO, result);
1847    let pos_inf = !finite & !self.is_sign_negative() & !nan_mask;
1848    result = pos_inf.blend(Self::infinity(), result);
1849    let neg_inf = !finite & self.is_sign_negative() & !nan_mask;
1850    result = neg_inf.blend(Self::ZERO, result);
1851    result
1852  }
1853
1854  #[inline]
1855  fn exponent(self) -> f64x4 {
1856    const_f64_as_f64x4!(pow2_52, 4503599627370496.0);
1857    const_f64_as_f64x4!(bias, 1023.0);
1858    let a = cast::<_, u64x4>(self);
1859    let b = a >> 52;
1860    let c = b | cast::<_, u64x4>(pow2_52);
1861    let d = cast::<_, f64x4>(c);
1862    let e = d - (pow2_52 + bias);
1863    e
1864  }
1865
1866  #[inline]
1867  fn fraction_2(self) -> Self {
1868    let t1 = cast::<_, u64x4>(self);
1869    let t2 = cast::<_, u64x4>(
1870      (t1 & u64x4::from(0x000FFFFFFFFFFFFF)) | u64x4::from(0x3FE0000000000000),
1871    );
1872    cast::<_, f64x4>(t2)
1873  }
1874  #[inline]
1875  fn is_zero_or_subnormal(self) -> Self {
1876    let t = cast::<_, i64x4>(self);
1877    let t = t & i64x4::splat(0x7FF0000000000000);
1878    let mask = t.simd_eq(i64x4::splat(0));
1879    cast::<_, f64x4>(mask)
1880  }
1881  #[inline]
1882  fn infinity() -> Self {
1883    cast::<_, f64x4>(i64x4::splat(0x7FF0000000000000))
1884  }
1885  #[inline]
1886  fn nan_log() -> Self {
1887    cast::<_, f64x4>(i64x4::splat(0x7FF8000000000000 | 0x101 << 29))
1888  }
1889  #[inline]
1890  fn nan_pow() -> Self {
1891    cast::<_, f64x4>(i64x4::splat(0x7FF8000000000000 | 0x101 << 29))
1892  }
1893
1894  /// Returns true for each element if it has a positive sign, including `+0.0`,
1895  /// `NaN`s with positive sign bit and positive infinity.
1896  #[inline]
1897  #[must_use]
1898  pub fn is_sign_positive(self) -> Self {
1899    const SIGN_MASK: u64x4 = u64x4::splat((-0.0_f64).to_bits());
1900
1901    let bits = cast::<f64x4, u64x4>(self);
1902    let sign = bits & SIGN_MASK;
1903    let result = sign.simd_eq(u64x4::ZERO);
1904    cast::<u64x4, f64x4>(result)
1905  }
1906
1907  /// Returns true for each element if it has a negative sign, including `-0.0`,
1908  /// `NaN`s with negative sign bit and negative infinity.
1909  #[inline]
1910  #[must_use]
1911  pub fn is_sign_negative(self) -> Self {
1912    const SIGN_MASK: u64x4 = u64x4::splat((-0.0_f64).to_bits());
1913
1914    let bits = cast::<f64x4, u64x4>(self);
1915    let sign = bits & SIGN_MASK;
1916    let result = sign.simd_eq(SIGN_MASK);
1917    cast::<u64x4, f64x4>(result)
1918  }
1919
1920  /// horizontal add of all the elements of the vector
1921  #[inline]
1922  pub fn reduce_add(self) -> f64 {
1923    pick! {
1924      if #[cfg(target_feature="avx")] {
1925        // From https://stackoverflow.com/questions/49941645/get-sum-of-values-stored-in-m256d-with-sse-avx
1926        let lo = cast_to_m128d_from_m256d(self.avx);
1927        let hi = extract_m128d_from_m256d::<1>(self.avx);
1928        let lo = add_m128d(lo,hi);
1929        let hi64 = unpack_high_m128d(lo,lo);
1930        let sum = add_m128d_s(lo,hi64);
1931        get_f64_from_m128d_s(sum)
1932      } else {
1933        self.a.reduce_add() + self.b.reduce_add()
1934      }
1935    }
1936  }
1937
1938  /// horizontal multiplication of all the elements of the vector
1939  #[inline]
1940  #[must_use]
1941  pub fn reduce_mul(self) -> f64 {
1942    pick! {
1943      if #[cfg(target_feature="avx")] {
1944        // From https://stackoverflow.com/questions/49941645/get-sum-of-values-stored-in-m256d-with-sse-avx
1945        let lo = cast_to_m128d_from_m256d(self.avx);
1946        let hi = extract_m128d_from_m256d::<1>(self.avx);
1947        let lo = mul_m128d(lo,hi);
1948        let hi64 = unpack_high_m128d(lo,lo);
1949        let product = mul_m128d_s(lo,hi64);
1950        get_f64_from_m128d_s(product)
1951      } else {
1952        self.a.reduce_mul() * self.b.reduce_mul()
1953      }
1954    }
1955  }
1956
1957  /// Natural log (ln(x))
1958  #[inline]
1959  #[must_use]
1960  pub fn ln(self) -> Self {
1961    const_f64_as_f64x4!(HALF, 0.5);
1962    const_f64_as_f64x4!(P0, 7.70838733755885391666E0);
1963    const_f64_as_f64x4!(P1, 1.79368678507819816313E1);
1964    const_f64_as_f64x4!(P2, 1.44989225341610930846E1);
1965    const_f64_as_f64x4!(P3, 4.70579119878881725854E0);
1966    const_f64_as_f64x4!(P4, 4.97494994976747001425E-1);
1967    const_f64_as_f64x4!(P5, 1.01875663804580931796E-4);
1968
1969    const_f64_as_f64x4!(Q0, 2.31251620126765340583E1);
1970    const_f64_as_f64x4!(Q1, 7.11544750618563894466E1);
1971    const_f64_as_f64x4!(Q2, 8.29875266912776603211E1);
1972    const_f64_as_f64x4!(Q3, 4.52279145837532221105E1);
1973    const_f64_as_f64x4!(Q4, 1.12873587189167450590E1);
1974    // LN2F_HI/LO from fdlibm (Freely Distributable LIBM)
1975    // Sun Microsystems, Inc. https://www.netlib.org/fdlibm/
1976    // e_log.c: bit-exact double-double decomposition of ln(2) for f64.
1977    // Replaced the original f32-literals (0.693359375, -2.12194440e-4)
1978    // which had ~10 significant digits, causing ~630 ULP error in f64 ln.
1979    const_f64_as_f64x4!(LN2F_HI, f64::from_bits(0x3FE62E42FEE00000));
1980    const_f64_as_f64x4!(LN2F_LO, f64::from_bits(0x3DEA39EF35793C76));
1981    const_f64_as_f64x4!(VM_SQRT2, 1.414213562373095048801);
1982    const_f64_as_f64x4!(VM_SMALLEST_NORMAL, 2.2250738585072014E-308);
1983
1984    let x1 = self;
1985    let x = Self::fraction_2(x1);
1986    let e = Self::exponent(x1);
1987    let mask = x.simd_gt(VM_SQRT2 * HALF);
1988    let x = (!mask).blend(x + x, x);
1989    let fe = mask.blend(e + Self::ONE, e);
1990    let x = x - Self::ONE;
1991    let px = polynomial_5!(x, P0, P1, P2, P3, P4, P5);
1992    let x2 = x * x;
1993    let px = x2 * x * px;
1994    let qx = polynomial_5n!(x, Q0, Q1, Q2, Q3, Q4);
1995    let res = px / qx;
1996    let res = fe.mul_add(LN2F_LO, res);
1997    let res = res + x2.mul_neg_add(HALF, x);
1998    let res = fe.mul_add(LN2F_HI, res);
1999    let overflow = !self.is_finite();
2000    let underflow = x1.simd_lt(VM_SMALLEST_NORMAL);
2001    let mask = overflow | underflow;
2002    if !mask.any() {
2003      res
2004    } else {
2005      let is_zero = self.is_zero_or_subnormal();
2006      let res = underflow.blend(Self::nan_log(), res);
2007      // Note: is_zero_or_subnormal() lumps subnormals (exponent==0) with zero.
2008      // Both get -Inf here. True subnormal inputs (~5e-324..2.225e-308) should
2009      // produce a finite negative result, but are vanishingly rare in
2010      // practice.
2011      let res = is_zero.blend(-Self::infinity(), res);
2012      let res = overflow.blend(self, res);
2013      // This must come *after* overflow.blend to overwrite ln(-∞) = -∞ to NaN
2014      let res = (!self.is_finite() & self.is_sign_negative())
2015        .blend(Self::nan_log(), res);
2016      res
2017    }
2018  }
2019
2020  /// Calculate `ln(1 + self)` for each lane.
2021  /// Accurate even for very small values.
2022  #[inline]
2023  #[must_use]
2024  pub fn ln_1p(self) -> Self {
2025    // Based on the identity ln(1+x) = x·ln(1+x)/((1+x)-1), i.e. x·ln(u)/(u-1)
2026    // where u = 1+x. From MUSL libc (Rich Felker et al., https://musl.libc.org) src/math/log1p.c
2027    // and fdlibm (Sun Microsystems, https://www.netlib.org/fdlibm/) s_log1p.c.
2028    // When 1+x rounds to 1 exactly (subnormal x), return x directly.
2029    // When 1+x overflows (+inf), return ln(u) without correction.
2030    // Mathematically exact: compensates for the rounding loss in 1+x without
2031    // needing a series threshold.
2032    let u = self + Self::ONE;
2033    let eq = u.simd_eq(Self::ONE);
2034    let ln_u = Self::ln(u);
2035    let correction = self * (ln_u / (u - Self::ONE));
2036    let result = eq.blend(self, correction);
2037    let over = u.is_inf();
2038    over.blend(ln_u, result)
2039  }
2040
2041  #[inline]
2042  #[must_use]
2043  pub fn log2(self) -> Self {
2044    Self::ln(self) * Self::LOG2_E
2045  }
2046  #[inline]
2047  #[must_use]
2048  pub fn log10(self) -> Self {
2049    Self::ln(self) * Self::LOG10_E
2050  }
2051
2052  #[inline]
2053  #[must_use]
2054  pub fn pow_f64x4(self, y: Self) -> Self {
2055    const_f64_as_f64x4!(ln2d_hi, 0.693145751953125);
2056    const_f64_as_f64x4!(ln2d_lo, 1.42860682030941723212E-6);
2057    const_f64_as_f64x4!(P0log, 2.0039553499201281259648E1);
2058    const_f64_as_f64x4!(P1log, 5.7112963590585538103336E1);
2059    const_f64_as_f64x4!(P2log, 6.0949667980987787057556E1);
2060    const_f64_as_f64x4!(P3log, 2.9911919328553073277375E1);
2061    const_f64_as_f64x4!(P4log, 6.5787325942061044846969E0);
2062    const_f64_as_f64x4!(P5log, 4.9854102823193375972212E-1);
2063    const_f64_as_f64x4!(P6log, 4.5270000862445199635215E-5);
2064    const_f64_as_f64x4!(Q0log, 6.0118660497603843919306E1);
2065    const_f64_as_f64x4!(Q1log, 2.1642788614495947685003E2);
2066    const_f64_as_f64x4!(Q2log, 3.0909872225312059774938E2);
2067    const_f64_as_f64x4!(Q3log, 2.2176239823732856465394E2);
2068    const_f64_as_f64x4!(Q4log, 8.3047565967967209469434E1);
2069    const_f64_as_f64x4!(Q5log, 1.5062909083469192043167E1);
2070
2071    // Taylor expansion constants
2072    const_f64_as_f64x4!(p2, 1.0 / 2.0); // coefficients for Taylor expansion of exp
2073    const_f64_as_f64x4!(p3, 1.0 / 6.0);
2074    const_f64_as_f64x4!(p4, 1.0 / 24.0);
2075    const_f64_as_f64x4!(p5, 1.0 / 120.0);
2076    const_f64_as_f64x4!(p6, 1.0 / 720.0);
2077    const_f64_as_f64x4!(p7, 1.0 / 5040.0);
2078    const_f64_as_f64x4!(p8, 1.0 / 40320.0);
2079    const_f64_as_f64x4!(p9, 1.0 / 362880.0);
2080    const_f64_as_f64x4!(p10, 1.0 / 3628800.0);
2081    const_f64_as_f64x4!(p11, 1.0 / 39916800.0);
2082    const_f64_as_f64x4!(p12, 1.0 / 479001600.0);
2083    const_f64_as_f64x4!(p13, 1.0 / 6227020800.0);
2084
2085    let x1 = self.abs();
2086    let x = x1.fraction_2();
2087    let mask = x.simd_gt(f64x4::SQRT_2 * f64x4::HALF);
2088    let x = (!mask).blend(x + x, x);
2089    let x = x - f64x4::ONE;
2090    let x2 = x * x;
2091    let px = polynomial_6!(x, P0log, P1log, P2log, P3log, P4log, P5log, P6log);
2092    let px = px * x * x2;
2093    let qx = polynomial_6n!(x, Q0log, Q1log, Q2log, Q3log, Q4log, Q5log);
2094    let lg1 = px / qx;
2095
2096    let ef = x1.exponent();
2097    let ef = mask.blend(ef + f64x4::ONE, ef);
2098    let e1 = (ef * y).round();
2099    let yr = ef.mul_sub(y, e1);
2100
2101    let lg = f64x4::HALF.mul_neg_add(x2, x) + lg1;
2102    let x2err = (f64x4::HALF * x).mul_sub(x, f64x4::HALF * x2);
2103    let lg_err = f64x4::HALF.mul_add(x2, lg - x) - lg1;
2104
2105    let e2 = (lg * y * f64x4::LOG2_E).round();
2106    let v = lg.mul_sub(y, e2 * ln2d_hi);
2107    let v = e2.mul_neg_add(ln2d_lo, v);
2108    let v = v - (lg_err + x2err).mul_sub(y, yr * f64x4::LN_2);
2109
2110    let x = v;
2111    let e3 = (x * f64x4::LOG2_E).round();
2112    let x = e3.mul_neg_add(f64x4::LN_2, x);
2113    let z =
2114      polynomial_13!(x, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13)
2115        + f64x4::ONE;
2116    let ee = e1 + e2 + e3;
2117    let ei = cast::<_, i64x4>(ee.round_int());
2118    let ej = cast::<_, i64x4>(ei + (cast::<_, i64x4>(z) >> 52));
2119
2120    let overflow = cast::<_, f64x4>(!ej.simd_lt(i64x4::splat(0x07FF)))
2121      | ee.simd_gt(f64x4::splat(3000.0));
2122    let underflow = cast::<_, f64x4>(!ej.simd_gt(i64x4::splat(0x000)))
2123      | ee.simd_lt(f64x4::splat(-3000.0));
2124
2125    // Add exponent by integer addition
2126    let z = cast::<_, f64x4>(cast::<_, i64x4>(z) + (ei << 52));
2127
2128    // Check for overflow/underflow
2129    let z = if (overflow | underflow).any() {
2130      let z = underflow.blend(f64x4::ZERO, z);
2131      overflow.blend(Self::infinity(), z)
2132    } else {
2133      z
2134    };
2135
2136    // Check for self == 0
2137    let x_zero = self.is_zero_or_subnormal();
2138    let z = x_zero.blend(
2139      y.simd_lt(f64x4::ZERO).blend(
2140        Self::infinity(),
2141        y.simd_eq(f64x4::ZERO).blend(f64x4::ONE, f64x4::ZERO),
2142      ),
2143      z,
2144    );
2145
2146    let x_sign = self.is_sign_negative();
2147
2148    let z = if x_sign.any() {
2149      // Y into an integer
2150      let yi = y.simd_eq(y.round());
2151      // Is y odd?
2152      let y_odd = cast::<_, i64x4>(y.round_int() << 63).round_float();
2153      let z1 =
2154        yi.blend(z | y_odd, self.simd_eq(Self::ZERO).blend(z, Self::nan_pow()));
2155      x_sign.blend(z1, z)
2156    } else {
2157      z
2158    };
2159
2160    let x_finite = self.is_finite();
2161    let y_finite = y.is_finite();
2162    let e_finite = ee.is_finite();
2163
2164    if (x_finite & y_finite & (e_finite | x_zero)).all() {
2165      return z;
2166    }
2167
2168    (self.is_nan() | y.is_nan()).blend(self + y, z)
2169  }
2170  #[inline]
2171  pub fn powf(self, y: f64) -> Self {
2172    Self::pow_f64x4(self, f64x4::splat(y))
2173  }
2174
2175  // Sometimes used for `transpose`.
2176  #[must_use]
2177  #[inline]
2178  #[allow(dead_code)]
2179  pub(crate) fn unpack_lo(self, b: Self) -> Self {
2180    pick! {
2181      if #[cfg(target_feature="avx")] {
2182        // `unpack_lo_m256d` cannot be used because it actually performs a
2183        // different operation.
2184        let [aa, _]: [f64x2; 2] = cast(self);
2185        let [ba, _]: [f64x2; 2] = cast(b);
2186        cast([aa.unpack_lo(ba), aa.unpack_hi(ba)])
2187      } else {
2188        Self { a: self.a.unpack_lo(b.a), b: self.a.unpack_hi(b.a) }
2189      }
2190    }
2191  }
2192
2193  // Sometimes used for `transpose`.
2194  #[must_use]
2195  #[inline]
2196  #[allow(dead_code)]
2197  pub(crate) fn unpack_hi(self, b: Self) -> Self {
2198    pick! {
2199      if #[cfg(target_feature="avx")] {
2200        // `unpack_hi_m256d` cannot be used because it actually performs a
2201        // different operation.
2202        let [_, ab]: [f64x2; 2] = cast(self);
2203        let [_, bb]: [f64x2; 2] = cast(b);
2204        cast([ab.unpack_lo(bb), ab.unpack_hi(bb)])
2205      } else {
2206        Self { a: self.b.unpack_lo(b.b), b: self.b.unpack_hi(b.b) }
2207      }
2208    }
2209  }
2210
2211  /// Transpose matrix of 4x4 `f64` matrix.
2212  #[must_use]
2213  #[inline]
2214  pub fn transpose(data: [f64x4; 4]) -> [f64x4; 4] {
2215    pick! {
2216      if #[cfg(target_feature="avx")] {
2217        // Can this be optimized?
2218        let a = data[0].unpack_lo(data[2]);
2219        let b = data[1].unpack_lo(data[3]);
2220        let c = data[0].unpack_hi(data[2]);
2221        let d = data[1].unpack_hi(data[3]);
2222        [
2223          a.unpack_lo(b),
2224          a.unpack_hi(b),
2225          c.unpack_lo(d),
2226          c.unpack_hi(d),
2227        ]
2228      } else {
2229        #[inline(always)]
2230        fn transpose_column(data: &[f64x4; 4], index: usize) -> f64x4 {
2231          f64x4::new([
2232            data[0].as_array()[index],
2233            data[1].as_array()[index],
2234            data[2].as_array()[index],
2235            data[3].as_array()[index],
2236          ])
2237        }
2238
2239        [
2240          transpose_column(&data, 0),
2241          transpose_column(&data, 1),
2242          transpose_column(&data, 2),
2243          transpose_column(&data, 3),
2244        ]
2245      }
2246    }
2247  }
2248
2249  #[inline]
2250  pub fn to_array(self) -> [f64; 4] {
2251    cast(self)
2252  }
2253
2254  #[inline]
2255  pub fn as_array(&self) -> &[f64; 4] {
2256    cast_ref(self)
2257  }
2258
2259  #[inline]
2260  pub fn as_mut_array(&mut self) -> &mut [f64; 4] {
2261    cast_mut(self)
2262  }
2263
2264  #[inline]
2265  pub fn from_i32x4(v: i32x4) -> Self {
2266    pick! {
2267      if #[cfg(target_feature="avx")] {
2268        Self { avx: convert_to_m256d_from_i32_m128i(v.sse) }
2269      } else {
2270        Self::new([
2271          v.as_array()[0] as f64,
2272          v.as_array()[1] as f64,
2273          v.as_array()[2] as f64,
2274          v.as_array()[3] as f64,
2275        ])
2276      }
2277    }
2278  }
2279}
2280
2281impl From<i32x4> for f64x4 {
2282  #[inline]
2283  fn from(v: i32x4) -> Self {
2284    Self::from_i32x4(v)
2285  }
2286}
2287
2288impl Not for f64x4 {
2289  type Output = Self;
2290  #[inline]
2291  fn not(self) -> Self {
2292    pick! {
2293      if #[cfg(target_feature="avx")] {
2294        Self { avx: self.avx.not()  }
2295      } else {
2296        Self {
2297          a : self.a.not(),
2298          b : self.b.not(),
2299        }
2300      }
2301    }
2302  }
2303}