devela/num/float/wrapper/
shared.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
// devela::num::float::wrapper::shared
//
//! Shared methods.
//

#[allow(unused_imports)]
use super::super::shared_docs::*;
use crate::{concat as cc, iif, stringify as sfy, Float, Sign};

/// Implements methods independently of any features
///
/// $f:   the floating-point type.
/// $uf:  unsigned int type with the same bit-size.
/// $ie:  signed int type used for integer exponentiation.
/// $ue:  unsigned int type used for integer exponentiation and number of terms (u32).
/// $cap: the capability feature that enables the given implementation. E.g "_float_f32".
/// $cmp: the feature that enables some methods depending on Compare. E.g "_cmp_f32".
macro_rules! impl_float_shared {
    () => {
        impl_float_shared![
            (f32:u32, i32, u32):"_float_f32":"_cmp_f32",
            (f64:u64, i32, u32):"_float_f64":"_cmp_f64"
        ];
    };

    ($( ($f:ty:$uf:ty, $ie:ty, $ue:ty) : $cap:literal : $cmp:literal ),+) => {
        $( impl_float_shared![@$f:$uf, $ie, $ue, $cap:$cmp]; )+
    };
    (@$f:ty:$uf:ty, $ie:ty, $ue:ty, $cap:literal : $cmp:literal) => {
        #[doc = crate::doc_availability!(feature = $cap)]
        ///
        /// # *Common implementations with or without `std` or `libm`*.
        #[cfg(feature = $cap )]
        // #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = $cap)))]
        impl Float<$f> {
            /// The largest integer less than or equal to itself.
            /// # Formulation
            #[doc = crate::FORMULA_FLOOR!()]
            #[must_use]
            pub const fn const_floor(self) -> Float<$f> {
                let mut result = self.const_trunc().0;
                if self.0.is_sign_negative() && Float(self.0 - result).abs().0 > <$f>::EPSILON {
                    result -= 1.0;
                }
                Float(result)
            }

            /// The smallest integer greater than or equal to itself.
            /// # Formulation
            #[doc = FORMULA_CEIL!()]
            #[must_use]
            pub const fn const_ceil(self) -> Float<$f> {
                let mut result = self.const_trunc().0;
                if self.0.is_sign_positive() && Float(self.0 - result).abs().0 > <$f>::EPSILON {
                    result += 1.0;
                }
                Float(result)
            }

            /// The nearest integer to itself, default rounding
            ///
            /// This is the default [`round_ties_away`] implementation.
            #[must_use]
            pub const fn const_round(self) -> Float<$f> { self.const_round_ties_away() }

            /// The nearest integer to itself, rounding ties away from `0.0`.
            ///
            /// This is the default [`round`] implementation.
            ///
            /// # Formulation
            #[doc = FORMULA_ROUND_TIES_AWAY!()]
            #[must_use]
            pub const fn const_round_ties_away(self) -> Float<$f> {
                Float(self.0 +
                    Float(0.5 - 0.25 * <$f>::EPSILON).const_copysign(self.0).0)
                        .const_trunc()
            }

            /// Returns the nearest integer to `x`, rounding ties to the nearest even integer.
            /// # Formulation
            #[doc = FORMULA_ROUND_TIES_EVEN!()]
            #[must_use]
            pub const fn const_round_ties_even(self) -> Float<$f> {
                let r = self.const_round_ties_away();
                if r.0 % 2.0 == 0.0 {
                    r
                } else {
                    #[allow(clippy::float_cmp, reason = "IMPROVE")]
                    if Float(self.0 - r.0).abs().0 == 0.5 { // -0.5 < error_margin
                        Float(r.0 - self.const_signum().0)
                    } else {
                        r
                    }
                }
            }

            /// The integral part.
            /// This means that non-integer numbers are always truncated towards zero.
            ///
            /// # Formulation
            #[doc = FORMULA_TRUNC!()]
            ///
            /// This implementation uses bitwise manipulation to remove the fractional part
            /// of the floating-point number. The exponent is extracted, and a mask is
            /// created to remove the fractional part. The new bits are then used to create
            /// the truncated floating-point number.
            #[must_use]
            pub const fn const_trunc(self) -> Float<$f> {
                let bits = self.0.to_bits();
                const BIAS: $ie = Float::<$f>::BIAS as $ie;
                const SIG_BITS: $ie = Float::<$f>::SIGNIFICAND_BITS as $ie;
                const EXP_MASK: $uf = (1 << Float::<$f>::EXPONENT_BITS) - 1;

                #[allow(clippy::cast_possible_wrap)]
                let exponent = (((bits >> SIG_BITS) & EXP_MASK) as $ie) - BIAS;
                if exponent < 0 {
                    iif![self.0.is_sign_positive(); Float(0.0); Float(-0.0)]
                } else if exponent < SIG_BITS {
                    let mask = !(((1 as $uf) << (SIG_BITS - exponent)) - 1);
                    let new_bits = bits & mask;
                    Float(<$f>::from_bits(new_bits))
                } else {
                    self
                }
            }

            /// Returns the nearest integer, rounding ties to the nearest odd integer.
            /// # Formulation
            #[doc = FORMULA_ROUND_TIES_ODD!()]
            #[must_use]
            pub fn const_round_ties_odd(self) -> Float<$f> {
                let r = self.const_round_ties_away();
                iif![r.0 % 2.0 != 0.0; r ;
                    iif![(self - r).abs() == 0.5; r + self.const_signum(); r]]
            }

            /// Returns the nearest integer, rounding ties to the nearest odd integer.
            /// # Formulation
            #[doc = FORMULA_ROUND_TIES_ODD!()]
            #[must_use]
            pub fn round_ties_odd(self) -> Float<$f> {
                let r = self.round_ties_away();
                iif![r.0 % 2.0 != 0.0; r ;
                    iif![(self - r).abs() == 0.5; r + self.signum(); r]]
            }

            /// The fractional part.
            /// # Formulation
            #[doc = FORMULA_FRACT!()]
            #[must_use]
            pub const fn const_fract(self) -> Float<$f> {
                Float(self.0 - self.const_trunc().0)
            }

            /// The integral and fractional parts.
            /// # Formulation
            #[doc = FORMULA_SPLIT!()]
            #[must_use]
            pub const fn const_split(self) -> (Float<$f>, Float<$f>) {
                let trunc = self.const_trunc();
                (trunc, Float(self.0 - trunc.0))
            }

            /// A number that represents its sign, propagating `NaN`.
            #[must_use]
            pub const fn const_signum(self) -> Float<$f> {
                if self.0.is_nan() { Float(<$f>::NAN) } else { Self::ONE.const_copysign(self.0) }
            }

            /// A number composed of the magnitude of itself and the `sign` of other.
            #[must_use]
            pub const fn const_copysign(self, sign: $f) -> Float<$f> {
                const SIGN_MASK: $uf = <$uf>::MAX / 2 + 1;
                const VALUE_MASK: $uf = <$uf>::MAX / 2;
                let sign_bit = sign.to_bits() & SIGN_MASK;
                let value_bits = self.0.to_bits() & VALUE_MASK;
                Float(<$f>::from_bits(value_bits | sign_bit))
            }

            /// Returns the [`Sign`].
            #[must_use]
            pub const fn sign(self) -> Sign {
                if self.is_sign_positive() { Sign::Positive } else { Sign::Negative }
            }

            /// Returns the [`Sign`], returning [`None`][Sign::None] for zero
            #[must_use]
            pub const fn sign_nonzero(self) -> Sign {
                if self.is_zero() {
                    Sign::None
                } else if self.is_sign_positive() {
                    Sign::Positive
                } else {
                    Sign::Negative
                }
            }

            /// Returns `true` if `self` has a positive sign.
            #[must_use]
            pub const fn is_sign_positive(self) -> bool { self.0.is_sign_positive() }

            /// Returns `true` if `self` has a negative sign.
            #[must_use]
            pub const fn is_sign_negative(self) -> bool { self.0.is_sign_negative() }

            /// Returns `true` if `self` is 0.0 or -0.0.
            #[must_use]
            pub const fn is_zero(self) -> bool {
                let non_sign_bits_mask = !(<$uf>::MAX / 2 + 1);
                (self.0.to_bits() & non_sign_bits_mask) == 0
            }

            /// Returns `true` if `self` has a positive sign and is not zero.
            #[must_use]
            pub const fn is_sign_positive_nonzero(self) -> bool {
                !self.is_zero() && self.is_sign_positive()
            }

            /// Returns `true` if `self` has a negative sign and is not zero.
            #[must_use]
            pub const fn is_sign_negative_nonzero(self) -> bool {
                !self.is_zero() && self.is_sign_negative()
            }

            /// Computes `(x * mul + add)` normally.
            #[must_use]
            pub const fn mul_add_fallback(self, mul: $f, add: $f) -> Float<$f> {
                Float(self.0 * mul + add)
            }

            /// The euclidean division.
            // NOTE: [incorrect computations](https://github.com/rust-lang/rust/issues/107904)
            #[must_use]
            pub fn div_euclid(self, other: $f) -> Float<$f> {
                let q = Float(self.0 / other).trunc().0;
                if self.0 % other < 0.0 {
                    iif![other > 0.0; Float(q - 1.0); Float(q + 1.0)]
                } else {
                    Float(q)
                }
            }

            /// The least non-negative remainder of `self` % `other`.
            // NOTE: [yield inconsistent results](https://github.com/rust-lang/rust/issues/111405)
            // WAIT:1.85 [const_float_methods](https://github.com/rust-lang/rust/pull/133389)
            #[must_use]
            pub const fn rem_euclid(self, other: $f) -> Float<$f> {
                let r = self.0 % other;
                iif![r < 0.0; Float(r + Float(other).abs().0); Float(r)]
            }

            /// Returns `self` between `[min..=max]` scaled to a new range `[u..=v]`.
            ///
            /// Values of `self` outside of `[min..=max]` are not clamped
            /// and will result in extrapolation.
            ///
            /// # Formulation
            #[doc = FORMULA_SCALE!()]
            /// # Examples
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(45_", sfy![$f], ").scale(0., 360., 0., 1.), 0.125];"]]
            #[doc = cc!["assert_eq![Float(45_", sfy![$f], ").scale(0., 360., -1., 1.), -0.75];"]]
            #[doc = cc!["assert_eq![Float(0.125_", sfy![$f], ").scale(0., 1., 0., 360.), 45.];"]]
            #[doc = cc!["assert_eq![Float(-0.75_", sfy![$f], ").scale(-1., 1., 0., 360.), 45.];"]]
            /// ```
            #[must_use]
            pub const fn scale(self, min: $f, max: $f, u: $f, v: $f) -> Float<$f> {
                Float((v - u) * (self.0 - min) / (max - min) + u)
            }

            /// Calculates a linearly interpolated value between `u..=v`
            /// based on `self` as a percentage between `[0..=1]`.
            ///
            /// Values of `self` outside `[0..=1]` are not clamped
            /// and will result in extrapolation.
            ///
            /// # Formulation
            #[doc = FORMULA_LERP!()]
            /// # Example
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(0.5_", sfy![$f], ").lerp(40., 80.), 60.];"]]
            // TODO more examples extrapolated
            /// ```
            #[must_use]
            pub const fn lerp(self, u: $f, v: $f) -> Float<$f> {
                Float((1.0 - self.0) * u + self.0 * v)
            }

            /// $ 1 / \sqrt{x} $ the
            /// [fast inverse square root algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root).
            #[must_use]
            pub const fn fisr(self) -> Float<$f> {
                let (mut i, three_halfs, x2) = (self.0.to_bits(), 1.5, self.0 * 0.5);
                i = Self::FISR_MAGIC - (i >> 1);
                let y = <$f>::from_bits(i);
                Float(y * (three_halfs - (x2 * y * y)))
            }

            /// $ \sqrt{x} $ The square root calculated using the
            /// [Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method).
            #[must_use]
            pub const fn sqrt_nr(self) -> Float<$f> {
                if self.0 < 0.0 {
                    Self::NAN
                } else if self.0 == 0.0 {
                    Self::ZERO
                } else {
                    let mut guess = self.0;
                    let mut guess_next = 0.5 * (guess + self.0 / guess);
                    while Self(guess - guess_next).abs().0 > Self::NR_TOLERANCE {
                        guess = guess_next;
                        guess_next = 0.5 * (guess + self.0 / guess);
                    }
                    Float(guess_next)
                }
            }

            /// $ \sqrt{x} $ the square root calculated using the
            /// [fast inverse square root algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root).
            #[must_use]
            pub const fn sqrt_fisr(self) -> Float<$f> { Float(1.0 / self.fisr().0) }

            /// The hypothenuse (the euclidean distance) using the
            /// [fast inverse square root algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root).
            ///
            /// # Formulation
            #[doc = FORMULA_HYPOT_FISR!()]
            #[must_use]
            pub const fn hypot_fisr(self, y: $f) -> Float<$f> {
                Float(self.0 * self.0 + y * y).sqrt_fisr()
            }

            /// The hypothenuse (the euclidean distance) using the
            /// [Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method).
            ///
            /// # Formulation
            #[doc = FORMULA_HYPOT_NR!()]
            #[must_use]
            pub const fn hypot_nr(self, y: $f) -> Float<$f> {
                Float(self.0 * self.0 + y * y).sqrt_nr()
            }

            /// $ \sqrt\[3\]{x} $ The cubic root calculated using the
            /// [Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method).
            #[must_use]
            pub const fn cbrt_nr(self) -> Float<$f> {
                iif![self.0 == 0.0; return self];
                let mut guess = self.0;
                loop {
                    let next_guess = (2.0 * guess + self.0 / (guess * guess)) / 3.0;
                    if Float(next_guess - guess).abs().0 < Self::NR_TOLERANCE {
                        break Float(next_guess);
                    }
                    guess = next_guess;
                }
            }

            /// The factorial of the integer value `x`.
            ///
            /// The maximum values with a representable result are:
            /// 34 for `f32` and 170 for `f64`.
            ///
            /// Note that precision is poor for large values.
            #[must_use]
            pub const fn factorial(x: $ue) -> Float<$f> {
                let mut result = Self::ONE.0;
                // for i in 1..=x { result *= i as $f; }
                let mut i = 1;
                while i <= x {
                    result *= i as $f;
                    i += 1;
                }
                Float(result)
            }

            /// The absolute value of `self`.
            // WAIT:1.85 [const_float_methods](https://github.com/rust-lang/rust/pull/133389)
            #[must_use]
            pub const fn abs(self) -> Float<$f> {
                let mask = <$uf>::MAX / 2;
                Float(<$f>::from_bits(self.0.to_bits() & mask))
            }

            /// The negative absolute value of `self` (sets its sign to be negative).
            #[must_use]
            pub const fn neg_abs(self) -> Float<$f> {
                if self.is_sign_negative() { self } else { self.flip_sign() }
            }

            /// Flips its sign.
            #[must_use]
            pub const fn flip_sign(self) -> Float<$f> {
                let sign_bit_mask = <$uf>::MAX / 2 + 1;
                Float(<$f>::from_bits(self.0.to_bits() ^ sign_bit_mask))
            }

            /// Returns itself clamped between `min` and `max`, ignoring `NaN`.
            ///
            /// # Example
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(50.0_", sfy![$f], ").clamp(40., 80.), 50.];"]]
            #[doc = cc!["assert_eq![Float(100.0_", sfy![$f], ").clamp(40., 80.), 80.];"]]
            #[doc = cc!["assert_eq![Float(10.0_", sfy![$f], ").clamp(40., 80.), 40.];"]]
            /// ```
            /// See also: [`clamp_nan`][Self::clamp_nan], [`clamp_total`][Self::clamp_total].
            // WAIT:1.85 [const_float_methods](https://github.com/rust-lang/rust/pull/133389)
            #[must_use]
            pub const fn const_clamp(self, min: $f, max: $f) -> Float<$f> {
                self.const_max(min).const_min(max)
            }

            /// The maximum between itself and `other`, ignoring `NaN`.
            // WAIT:1.85 [const_float_methods](https://github.com/rust-lang/rust/pull/133389)
            #[must_use]
            pub const fn const_max(self, other: $f) -> Float<$f> {
                if self.0.is_nan() || self.0 < other { Float(other) } else { self }
            }

            /// The minimum between itself and other, ignoring `NaN`.
            // WAIT:1.85 [const_float_methods](https://github.com/rust-lang/rust/pull/133389)
            #[must_use]
            pub const fn const_min(self, other: $f) -> Float<$f> {
                if other.is_nan() || self.0 < other { self } else { Float(other) }
            }

            /// Returns itself clamped between `min` and `max`, using total order.
            ///
            /// # Example
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(50.0_", sfy![$f], ").clamp_total(40., 80.), 50.];"]]
            #[doc = cc!["assert_eq![Float(100.0_", sfy![$f], ").clamp_total(40., 80.), 80.];"]]
            #[doc = cc!["assert_eq![Float(10.0_", sfy![$f], ").clamp_total(40., 80.), 40.];"]]
            /// ```
            /// See also: [`clamp`][Self::clamp], [`clamp_nan`][Self::clamp_nan].
            #[must_use]
            #[cfg(feature = $cmp)]
            #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = $cmp)))]
            pub const fn clamp_total(self, min: $f, max: $f) -> Float<$f> {
                Float(crate::Compare(self.0).clamp(min, max))
            }

            /// Returns the maximum between itself and `other`, using total order.
            ///
            /// See also: [`max_nan`][Self::max_nan].
            #[must_use]
            #[cfg(feature = $cmp)]
            #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = $cmp)))]
            pub const fn max_total(self, other: $f) -> Float<$f> {
                Float(crate::Compare(self.0).max(other))
            }

            /// Returns the minimum between itself and `other`, using total order.
            ///
            /// See also: [`min_nan`][Self::min_nan].
            #[must_use]
            #[cfg(feature = $cmp)]
            #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = $cmp)))]
            pub fn min_total(self, other: $f) -> Float<$f> {
                Float(crate::Compare(self.0).min(other))
            }

            /// Returns itself clamped between `min` and `max`, propagating `NaN`.
            ///
            /// # Example
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(50.0_", sfy![$f], ").clamp_nan(40., 80.), 50.];"]]
            #[doc = cc!["assert_eq![Float(100.0_", sfy![$f], ").clamp_nan(40., 80.), 80.];"]]
            #[doc = cc!["assert_eq![Float(10.0_", sfy![$f], ").clamp_nan(40., 80.), 40.];"]]
            /// ```
            /// See also: [`clamp`][Self::clamp], [`clamp_total`][Self::clamp_total].
            #[must_use]
            pub const fn clamp_nan(self, min: $f, max: $f) -> Float<$f> {
                self.max_nan(min).min_nan(max)
            }

            /// Returns the maximum between itself and `other`, propagating `Nan`.
            ///
            /// # Example
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(50.0_", sfy![$f], ").max_nan(80.), 80.];"]]
            #[doc = cc!["assert_eq![Float(100.0_", sfy![$f], ").max_nan(80.), 100.];"]]
            /// ```
            /// See also: [`max_total`][Self::max_total].
            // WAIT: [float_minimum_maximum](https://github.com/rust-lang/rust/issues/91079)
            #[must_use]
            #[expect(clippy::float_cmp, reason = "TODO:CHECK:IMPROVE?")]
            pub const fn max_nan(self, other: $f) -> Float<$f> {
                if self.0 > other {
                    self
                } else if self.0 < other {
                    Float(other)
                } else if self.0 == other {
                    iif![self.is_sign_positive() && other.is_sign_negative(); self; Float(other)]
                } else {
                    // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
                    Float(self.0 + other)
                }
            }

            /// Returns the minimum between itself and `other`, propagating `Nan`.
            ///
            /// # Example
            /// ```
            /// # use devela::Float;
            #[doc = cc!["assert_eq![Float(50.0_", sfy![$f], ").min_nan(80.), 50.];"]]
            #[doc = cc!["assert_eq![Float(100.0_", sfy![$f], ").min_nan(80.), 80.];"]]
            /// ```
            /// See also: [`min_total`][Self::min_total].
            // WAIT: [float_minimum_maximum](https://github.com/rust-lang/rust/issues/91079)
            #[must_use]
            #[expect(clippy::float_cmp, reason = "TODO:CHECK:IMPROVE?")]
            pub const fn min_nan(self, other: $f) -> Float<$f> {
                if self.0 < other {
                    self
                } else if self.0 > other {
                    Float(other)
                } else if self.0 == other {
                    iif![self.is_sign_negative() && other.is_sign_positive(); self; Float(other)]
                } else {
                    // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
                    Float(self.0 + other)
                }
            }

            /// Raises itself to the `p` integer power.
            #[must_use]
            pub const fn const_powi(self, p: $ie) -> Float<$f> {
                match p {
                    0 => Self::ONE,
                    1.. => {
                        let mut result = self.0;
                        let mut i = 1;
                        while i < p {
                            result *= self.0;
                            i += 1;
                        }
                        Float(result)
                    }
                    _ => {
                        let mut result = self.0;
                        let mut i = 1;
                        let abs_p = p.abs();
                        while i < abs_p {
                            result /= self.0;
                            i += 1;
                        }
                        Float(result)
                    }
                }
            }

            /// Evaluates a polynomial at the `self` point value, using [Horner's method].
            ///
            /// Expects a slice of `coefficients` $[a_n, a_{n-1}, ..., a_1, a_0]$
            /// representing the polynomial $ a_n * x^n + a_{n-1} * x^{(n-1)} + ... + a_1 * x + a_0 $.
            ///
            /// # Examples
            /// ```
            /// # use devela::Float;
            /// let coefficients = [2.0, -6.0, 2.0, -1.0];
            #[doc = cc!["assert_eq![Float(3.0_", sfy![$f], ").eval_poly(&coefficients), 5.0];"]]
            #[doc = cc!["assert_eq![Float(3.0_", sfy![$f], ").eval_poly(&[]), 0.0];"]]
            /// ```
            ///
            /// [Horner's method]: https://en.wikipedia.org/wiki/Horner%27s_method#Polynomial_evaluation_and_long_division
            // WAIT: [for-loops in constants](https://github.com/rust-lang/rust/issues/87575)
            #[must_use]
            pub const fn eval_poly(self, coefficients: &[$f]) -> Float<$f> {
                let coef = coefficients;
                match coef.len() {
                    0 => Float(0.0),
                    1 => Float(coef[0]),
                    _ => {
                        let mut result = coef[0];
                        // non-const version:
                        // for &c in &coef[1..] {
                        //     result = result * self.0 + c;
                        // }
                        // const version:
                        let mut i = 1;
                        while i < coef.len() {
                            result = result * self.0 + coef[i];
                            i += 1;
                        }
                        Float(result)
                    }
                }
            }

            /// Approximates the derivative of the 1D function `f` at `x` point using step size `h`.
            ///
            /// Uses the [finite difference method].
            ///
            /// # Formulation
            #[doc = FORMULA_DERIVATIVE!()]
            ///
            /// See also the [`autodiff`] attr macro, enabled with the `nightly_autodiff` feature.
            ///
            /// [finite difference method]: https://en.wikipedia.org/wiki/Finite_difference_method
            /// [`autodiff`]: crate::autodiff
            pub fn derivative<F>(f: F, x: $f, h: $f) -> Float<$f>
            where
                F: Fn($f) -> $f,
            {
                Float((f(x + h) - f(x)) / h)
            }

            /// Approximates the integral of the 1D function `f` over the range `[x, y]`
            /// using `n` subdivisions.
            ///
            /// Uses the [Riemann Sum](https://en.wikipedia.org/wiki/Riemann_sum).
            ///
            /// # Formulation
            #[doc = FORMULA_INTEGRATE!()]
            pub fn integrate<F>(f: F, x: $f, y: $f, n: usize) -> Float<$f>
            where
                F: Fn($f) -> $f,
            {
                let dx = (y - x) / n as $f;
                Float(
                    (0..n)
                    .map(|i| { let x = x + i as $f * dx; f(x) * dx })
                    .sum()
                )
            }

            /// Approximates the partial derivative of the 2D function `f` at point (`x`, `y`)
            /// with step size `h`, differentiating over `x`.
            ///
            /// # Formulation
            #[doc = FORMULA_PARTIAL_DERIVATIVE_X!()]
            pub fn partial_derivative_x<F>(f: F, x: $f, y: $f, h: $f) -> Float<$f>
            where
                F: Fn($f, $f) -> $f,
            {
                Float((f(x + h, y) - f(x, y)) / h)
            }

            /// Approximates the partial derivative of the 2D function `f` at point (`x`, `y`)
            /// with step size `h`, differentiating over `x`.
            ///
            /// # Formulation
            #[doc = FORMULA_PARTIAL_DERIVATIVE_Y!()]
            pub fn partial_derivative_y<F>(f: F, x: $f, y: $f, h: $f) -> Float<$f>
            where
                F: Fn($f, $f) -> $f,
            {
                Float((f(x, y + h) - f(x, y)) / h)
            }
        }
    };
}
impl_float_shared!();