Skip to main content

miri/
math.rs

1use std::ops::Neg;
2
3use rand::RngExt;
4use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, Semantics, SingleS};
5use rustc_apfloat::{Float, FloatConvert};
6use rustc_middle::ty::{self, FloatTy, ScalarInt};
7
8use crate::*;
9
10/// Convert a softfloat type to its corresponding hostfloat type.
11pub trait ToHost {
12    type HostFloat;
13    fn to_host(self) -> Self::HostFloat;
14}
15
16/// Convert a hostfloat type to its corresponding softfloat type.
17pub trait ToSoft {
18    type SoftFloat;
19    fn to_soft(self) -> Self::SoftFloat;
20}
21
22impl ToHost for rustc_apfloat::ieee::Double {
23    type HostFloat = f64;
24
25    fn to_host(self) -> Self::HostFloat {
26        f64::from_bits(self.to_bits().try_into().unwrap())
27    }
28}
29
30impl ToSoft for f64 {
31    type SoftFloat = rustc_apfloat::ieee::Double;
32
33    fn to_soft(self) -> Self::SoftFloat {
34        Float::from_bits(self.to_bits().into())
35    }
36}
37
38impl ToHost for rustc_apfloat::ieee::Single {
39    type HostFloat = f32;
40
41    fn to_host(self) -> Self::HostFloat {
42        f32::from_bits(self.to_bits().try_into().unwrap())
43    }
44}
45
46impl ToSoft for f32 {
47    type SoftFloat = rustc_apfloat::ieee::Single;
48
49    fn to_soft(self) -> Self::SoftFloat {
50        Float::from_bits(self.to_bits().into())
51    }
52}
53
54impl ToHost for rustc_apfloat::ieee::Half {
55    type HostFloat = f16;
56
57    fn to_host(self) -> Self::HostFloat {
58        f16::from_bits(self.to_bits().try_into().unwrap())
59    }
60}
61
62impl ToSoft for f16 {
63    type SoftFloat = rustc_apfloat::ieee::Half;
64
65    fn to_soft(self) -> Self::SoftFloat {
66        Float::from_bits(self.to_bits().into())
67    }
68}
69
70/// Disturbes a floating-point result by a relative error in the range (-2^scale, 2^scale).
71pub(crate) fn apply_random_float_error<F: rustc_apfloat::Float>(
72    ecx: &mut crate::MiriInterpCx<'_>,
73    val: F,
74    err_scale: i32,
75) -> F {
76    if !ecx.machine.float_nondet
77        || matches!(ecx.machine.float_rounding_error, FloatRoundingErrorMode::None)
78        // relative errors don't do anything to zeros... avoid messing up the sign
79        || val.is_zero()
80        // The logic below makes no sense if the input is already non-finite.
81        || !val.is_finite()
82    {
83        return val;
84    }
85    let rng = ecx.machine.rng.get_mut();
86
87    // Generate a random integer in the range [0, 2^PREC).
88    // (When read as binary, the position of the first `1` determines the exponent,
89    // and the remaining bits fill the mantissa. `PREC` is one plus the size of the mantissa,
90    // so this all works out.)
91    let r = F::from_u128(match ecx.machine.float_rounding_error {
92        FloatRoundingErrorMode::Random => rng.random_range(0..(1 << F::PRECISION)),
93        FloatRoundingErrorMode::Max => (1 << F::PRECISION) - 1, // force max error
94        FloatRoundingErrorMode::None => unreachable!(),
95    })
96    .value;
97    // Multiply this with 2^(scale - PREC). The result is between 0 and
98    // 2^PREC * 2^(scale - PREC) = 2^scale.
99    let err = r.scalbn(err_scale.strict_sub(F::PRECISION.try_into().unwrap()));
100    // give it a random sign
101    let err = if rng.random() { -err } else { err };
102    // Compute `val*(1+err)`, distributed out as `val + val*err` to avoid the imprecise addition
103    // error being amplified by multiplication.
104    (val + (val * err).value).value
105}
106
107/// Applies an error of `[-N, +N]` ULP to the given value.
108pub(crate) fn apply_random_float_error_ulp<F: rustc_apfloat::Float>(
109    ecx: &mut crate::MiriInterpCx<'_>,
110    val: F,
111    max_error: u32,
112) -> F {
113    // We could try to be clever and reuse `apply_random_float_error`, but that is hard to get right
114    // (see <https://github.com/rust-lang/miri/pull/4558#discussion_r2316838085> for why) so we
115    // implement the logic directly instead.
116    if !ecx.machine.float_nondet
117        || matches!(ecx.machine.float_rounding_error, FloatRoundingErrorMode::None)
118        // FIXME: also disturb zeros? That requires a lot more cases in `fixed_float_value`
119        // and might make the std test suite quite unhappy.
120        || val.is_zero()
121        // The logic below makes no sense if the input is already non-finite.
122        || !val.is_finite()
123    {
124        return val;
125    }
126    let rng = ecx.machine.rng.get_mut();
127
128    let max_error = i64::from(max_error);
129    let error = match ecx.machine.float_rounding_error {
130        FloatRoundingErrorMode::Random => rng.random_range(-max_error..=max_error),
131        FloatRoundingErrorMode::Max =>
132            if rng.random() {
133                max_error
134            } else {
135                -max_error
136            },
137        FloatRoundingErrorMode::None => unreachable!(),
138    };
139    // If upwards ULP and downwards ULP differ, we take the average.
140    let ulp = (((val.next_up().value - val).value + (val - val.next_down().value).value).value
141        / F::from_u128(2).value)
142        .value;
143    // Shift the value by N times the ULP
144    (val + (ulp * F::from_i128(error.into()).value).value).value
145}
146
147/// Applies an error of `[-N, +N]` ULP to the given value.
148/// Will fail if `val` is not a floating point number.
149pub(crate) fn apply_random_float_error_to_imm<'tcx>(
150    ecx: &mut MiriInterpCx<'tcx>,
151    val: ImmTy<'tcx>,
152    max_error: u32,
153) -> InterpResult<'tcx, ImmTy<'tcx>> {
154    let scalar = val.to_scalar_int()?;
155    let res: ScalarInt = match val.layout.ty.kind() {
156        ty::Float(FloatTy::F16) =>
157            apply_random_float_error_ulp(ecx, scalar.to_f16(), max_error).into(),
158        ty::Float(FloatTy::F32) =>
159            apply_random_float_error_ulp(ecx, scalar.to_f32(), max_error).into(),
160        ty::Float(FloatTy::F64) =>
161            apply_random_float_error_ulp(ecx, scalar.to_f64(), max_error).into(),
162        ty::Float(FloatTy::F128) =>
163            apply_random_float_error_ulp(ecx, scalar.to_f128(), max_error).into(),
164        _ => bug!("intrinsic called with non-float input type"),
165    };
166
167    interp_ok(ImmTy::from_scalar_int(res, val.layout))
168}
169
170/// Remove `f16`/`f32`/`f64`/`f128` suffix, if any.
171///
172/// Also strip trailing `f` (indicates "float"), with an exception for "erf" to avoid
173/// removing that `f`.
174fn strip_float_suffix(intrinsic_name: &str) -> &str {
175    let name = intrinsic_name
176        .strip_suffix("f16")
177        .or_else(|| intrinsic_name.strip_suffix("f32"))
178        .or_else(|| intrinsic_name.strip_suffix("f64"))
179        .or_else(|| intrinsic_name.strip_suffix("f128"))
180        .unwrap_or(intrinsic_name);
181
182    if name == "erf" { name } else { name.strip_suffix("f").unwrap_or(name) }
183}
184
185/// Given a floating-point operation and a floating-point value, clamps the result to the output
186/// range of the given operation according to the C standard ([C23 Section 7.12]), if any.
187///
188/// [C23 Section 7.12]: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#section.7.12
189pub(crate) fn clamp_float_value<S: Semantics>(
190    intrinsic_name: &str,
191    val: IeeeFloat<S>,
192) -> IeeeFloat<S>
193where
194    IeeeFloat<S>: IeeeExt,
195{
196    let zero = IeeeFloat::<S>::ZERO;
197    let one = IeeeFloat::<S>::one();
198    let two = IeeeFloat::<S>::two();
199    let pi = IeeeFloat::<S>::pi();
200    let pi_over_2 = (pi / two).value;
201
202    match strip_float_suffix(intrinsic_name) {
203        // sin, cos, tanh: [-1, 1]
204        "sin" | "cos" | "tanh" => val.clamp(one.neg(), one),
205
206        // exp: [0, +INF)
207        "exp" | "exp2" => val.maximum(zero),
208
209        // cosh: [1, +INF)
210        "cosh" => val.maximum(one),
211
212        // acos: [0, π]
213        "acos" => val.clamp(zero, pi),
214
215        // asin: [-π/2, +π/2]
216        "asin" => val.clamp(pi_over_2.neg(), pi_over_2),
217
218        // atan: [-π/2, +π/2]
219        "atan" => val.clamp(pi_over_2.neg(), pi_over_2),
220
221        // erfc: [-1, 1]
222        "erf" => val.clamp(one.neg(), one),
223
224        // erfc: [0, 2]
225        "erfc" => val.clamp(zero, two),
226
227        // atan2(y, x): arctan(y/x) in [−π, +π]
228        "atan2" => val.clamp(pi.neg(), pi),
229
230        _ => val,
231    }
232}
233
234/// For the intrinsics:
235/// - sin, sinhf, sinh
236/// - cos, coshf, cosh
237/// - tanhf, tanh, atanf, atan, atan2f, atan2
238/// - exp, exp2
239/// - log, log2, log10
240/// - powf
241/// - erff, erf, erfcf, erfc
242/// - hypotf, hypot
243///
244/// # Return
245///
246/// Returns `Some(output)` if the `intrinsic` results in a defined fixed `output` specified in the C standard
247/// (specifically, [C23 annex F.10])  when given `args` as arguments. Outputs that are unaffected by a relative error
248/// (such as INF and zero) are not handled here, they are assumed to be handled by the underlying
249/// implementation. Returns `None` if no specific value is guaranteed.
250///
251/// [C23 annex F.10]: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#section.13.10
252///
253/// # Note
254///
255/// For `powf*` operations of the form:
256///
257/// - `(SNaN)^(±0)`
258/// - `1^(SNaN)`
259///
260/// The result is implementation-defined:
261/// - musl returns for both `1.0`
262/// - glibc returns for both `NaN`
263///
264/// This discrepancy exists because SNaN handling is not consistently defined across platforms,
265/// and the C standard leaves behavior for SNaNs unspecified.
266///
267/// Miri chooses to adhere to both implementations and returns either one of them non-deterministically.
268pub(crate) fn fixed_float_value<S: Semantics>(
269    ecx: &mut MiriInterpCx<'_>,
270    intrinsic_name: &str,
271    args: &[IeeeFloat<S>],
272) -> Option<IeeeFloat<S>>
273where
274    IeeeFloat<S>: IeeeExt,
275{
276    let ecx = ecx.eval_context_mut();
277    let one = IeeeFloat::<S>::one();
278    let two = IeeeFloat::<S>::two();
279    let three = IeeeFloat::<S>::three();
280    let pi = IeeeFloat::<S>::pi();
281    let pi_over_2 = (pi / two).value;
282    let pi_over_4 = (pi_over_2 / two).value;
283
284    Some(match (strip_float_suffix(intrinsic_name), args) {
285        // cos(±0) and cosh(±0)= 1
286        ("cos" | "cosh", [input]) if input.is_zero() => one,
287
288        // e^0 = 1
289        ("exp" | "exp2", [input]) if input.is_zero() => one,
290
291        // tanh(±INF) = ±1
292        ("tanh", [input]) if input.is_infinite() => one.copy_sign(*input),
293
294        // atan(±INF) = ±π/2
295        ("atan", [input]) if input.is_infinite() => pi_over_2.copy_sign(*input),
296
297        // erf(±INF) = ±1
298        ("erf", [input]) if input.is_infinite() => one.copy_sign(*input),
299
300        // erfc(-INF) = 2
301        ("erfc", [input]) if input.is_neg_infinity() => (one + one).value,
302
303        // hypot(x, ±0) = abs(x), if x is not a NaN.
304        // `_hypot` is the Windows name for this.
305        ("_hypot" | "hypot", [x, y]) if !x.is_nan() && y.is_zero() => x.abs(),
306
307        // atan2 has many cases, but NaNs are excluded from all of them. It's easiest
308        // to handle that upfront.
309        ("atan2", [x, y]) if x.is_nan() || y.is_nan() => return None,
310
311        // atan2(±0,−0) = ±π.
312        // atan2(±0, y) = ±π for y < 0.
313        ("atan2", [x, y]) if (x.is_zero() && y.is_negative()) => pi.copy_sign(*x),
314
315        // atan2(±x,−∞) = ±π for finite x > 0.
316        ("atan2", [x, y]) if (!x.is_zero() && !x.is_infinite()) && y.is_neg_infinity() =>
317            pi.copy_sign(*x),
318
319        // atan2(x, ±0) = −π/2 for x < 0.
320        // atan2(x, ±0) =  π/2 for x > 0.
321        ("atan2", [x, y]) if !x.is_zero() && y.is_zero() => pi_over_2.copy_sign(*x),
322
323        //atan2(±∞, −∞) = ±3π/4
324        ("atan2", [x, y]) if x.is_infinite() && y.is_neg_infinity() =>
325            (pi_over_4 * three).value.copy_sign(*x),
326
327        //atan2(±∞, +∞) = ±π/4
328        ("atan2", [x, y]) if x.is_infinite() && y.is_pos_infinity() => pi_over_4.copy_sign(*x),
329
330        // atan2(±∞, y) returns ±π/2 for finite y.
331        ("atan2", [x, y]) if x.is_infinite() && !y.is_infinite() => pi_over_2.copy_sign(*x),
332
333        // (-1)^(±INF) = 1
334        ("pow", [base, exp]) if *base == -one && exp.is_infinite() => one,
335
336        // 1^y = 1 for any y, even a NaN
337        ("pow", [base, exp]) if *base == one => {
338            let rng = ecx.machine.rng.get_mut();
339            // SNaN exponents get special treatment: they might return 1, or a NaN.
340            // This is non-deterministic because LLVM can treat SNaN as QNaN, and because
341            // implementation behavior differs between glibc and musl.
342            let return_nan = exp.is_signaling() && ecx.machine.float_nondet && rng.random();
343            if return_nan { ecx.generate_nan(args) } else { one }
344        }
345
346        // x^(±0) = 1 for any x, even a NaN
347        ("pow", [base, exp]) if exp.is_zero() => {
348            let rng = ecx.machine.rng.get_mut();
349            // SNaN bases get special treatment: they might return 1, or a NaN.
350            // This is non-deterministic because LLVM can treat SNaN as QNaN, and because
351            // implementation behavior differs between glibc and musl.
352            let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random();
353            if return_nan { ecx.generate_nan(args) } else { one }
354        }
355
356        // There are a lot of cases for fixed outputs according to the C Standard, but these are
357        // mainly INF or zero which are not affected by the applied error.
358        _ => return None,
359    })
360}
361
362/// Returns `Some(output)` if `powi` (called `pown` in C) results in a fixed value specified in the
363/// C standard (specifically, C23 annex F.10.4.6) when doing `base^exp`. Otherwise, returns `None`.
364pub(crate) fn fixed_powi_value<S: Semantics>(
365    ecx: &mut MiriInterpCx<'_>,
366    base: IeeeFloat<S>,
367    exp: i32,
368) -> Option<IeeeFloat<S>>
369where
370    IeeeFloat<S>: IeeeExt,
371{
372    match exp {
373        0 => {
374            let one = IeeeFloat::<S>::one();
375            let rng = ecx.machine.rng.get_mut();
376            // SNaN bases get special treatment: they might return 1, or a NaN.
377            // This is non-deterministic because LLVM can treat SNaN as QNaN.
378            let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random();
379            Some(if return_nan { ecx.generate_nan(&[base]) } else { one })
380        }
381
382        _ => None,
383    }
384}
385
386pub(crate) fn sqrt<F: Float>(x: F) -> F {
387    match x.category() {
388        // preserve zero sign
389        rustc_apfloat::Category::Zero => x,
390        // propagate NaN
391        rustc_apfloat::Category::NaN => x,
392        // sqrt of negative number is NaN
393        _ if x.is_negative() => F::NAN,
394        // sqrt(∞) = ∞
395        rustc_apfloat::Category::Infinity => F::INFINITY,
396        rustc_apfloat::Category::Normal => {
397            // Floating point precision, excluding the integer bit
398            let prec = i32::try_from(F::PRECISION).unwrap() - 1;
399
400            // x = 2^(exp - prec) * mant
401            // where mant is an integer with prec+1 bits
402            // mant is a u128, which should be large enough for the largest prec (112 for f128)
403            let mut exp = x.ilogb();
404            let mut mant = x.scalbn(prec - exp).to_u128(128).value;
405
406            if exp % 2 != 0 {
407                // Make exponent even, so it can be divided by 2
408                exp -= 1;
409                mant <<= 1;
410            }
411
412            // Bit-by-bit (base-2 digit-by-digit) sqrt of mant.
413            // mant is treated here as a fixed point number with prec fractional bits.
414            // mant will be shifted left by one bit to have an extra fractional bit, which
415            // will be used to determine the rounding direction.
416
417            // res is the truncated sqrt of mant, where one bit is added at each iteration.
418            let mut res = 0u128;
419            // rem is the remainder with the current res
420            // rem_i = 2^i * ((mant<<1) - res_i^2)
421            // starting with res = 0, rem = mant<<1
422            let mut rem = mant << 1;
423            // s_i = 2*res_i
424            let mut s = 0u128;
425            // d is used to iterate over bits, from high to low (d_i = 2^(-i))
426            let mut d = 1u128 << (prec + 1);
427
428            // For iteration j=i+1, we need to find largest b_j = 0 or 1 such that
429            //  (res_i + b_j * 2^(-j))^2 <= mant<<1
430            // Expanding (a + b)^2 = a^2 + b^2 + 2*a*b:
431            //  res_i^2 + (b_j * 2^(-j))^2 + 2 * res_i * b_j * 2^(-j) <= mant<<1
432            // And rearranging the terms:
433            //  b_j^2 * 2^(-j) + 2 * res_i * b_j <= 2^j * (mant<<1 - res_i^2)
434            //  b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i
435
436            while d != 0 {
437                // Probe b_j^2 * 2^(-j) + 2 * res_i * b_j <= rem_i with b_j = 1:
438                // t = 2*res_i + 2^(-j)
439                let t = s + d;
440                if rem >= t {
441                    // b_j should be 1, so make res_j = res_i + 2^(-j) and adjust rem
442                    res += d;
443                    s += d + d;
444                    rem -= t;
445                }
446                // Adjust rem for next iteration
447                rem <<= 1;
448                // Shift iterator
449                d >>= 1;
450            }
451
452            // Remove extra fractional bit from result, rounding to nearest.
453            // If the last bit is 0, then the nearest neighbor is definitely the lower one.
454            // If the last bit is 1, it sounds like this may either be a tie (if there's
455            // infinitely many 0s after this 1), or the nearest neighbor is the upper one.
456            // However, since square roots are either exact or irrational, and an exact root
457            // would lead to the last "extra" bit being 0, we can exclude a tie in this case.
458            // We therefore always round up if the last bit is 1. When the last bit is 0,
459            // adding 1 will not do anything since the shift will discard it.
460            res = (res + 1) >> 1;
461
462            // Build resulting value with res as mantissa and exp/2 as exponent
463            F::from_u128(res).value.scalbn(exp / 2 - prec)
464        }
465    }
466}
467
468pub fn sqrt_op<'tcx, F: Float + FloatConvert<F> + Into<Scalar>>(
469    ecx: &mut MiriInterpCx<'tcx>,
470    f: &OpTy<'tcx>,
471    dest: &PlaceTy<'tcx>,
472) -> InterpResult<'tcx> {
473    let f: F = ecx.read_scalar(f)?.to_float()?;
474    // Sqrt is specified to be fully precise.
475    let res = math::sqrt(f);
476    let res = ecx.adjust_nan(res, &[f]);
477    ecx.write_scalar(res, dest)
478}
479
480pub trait HostFloatOperation {
481    fn host_sin(self) -> Self;
482    fn host_cos(self) -> Self;
483    fn host_exp(self) -> Self;
484    fn host_exp2(self) -> Self;
485    fn host_log(self) -> Self;
486    fn host_log10(self) -> Self;
487    fn host_log2(self) -> Self;
488    fn host_powf(self, y: Self) -> Self;
489    fn host_powi(self, y: i32) -> Self;
490}
491
492macro_rules! impl_float_host_operations {
493    ($ty:ty) => {
494        impl HostFloatOperation for $ty {
495            fn host_sin(self) -> Self {
496                self.to_host().sin().to_soft()
497            }
498            fn host_cos(self) -> Self {
499                self.to_host().cos().to_soft()
500            }
501            fn host_exp(self) -> Self {
502                self.to_host().exp().to_soft()
503            }
504            fn host_exp2(self) -> Self {
505                self.to_host().exp2().to_soft()
506            }
507            fn host_log(self) -> Self {
508                self.to_host().ln().to_soft()
509            }
510            fn host_log10(self) -> Self {
511                self.to_host().log10().to_soft()
512            }
513            fn host_log2(self) -> Self {
514                self.to_host().log2().to_soft()
515            }
516            fn host_powf(self, y: Self) -> Self {
517                self.to_host().powf(y.to_host()).to_soft()
518            }
519            fn host_powi(self, y: i32) -> Self {
520                self.to_host().powi(y).to_soft()
521            }
522        }
523    };
524}
525
526impl_float_host_operations!(IeeeFloat<HalfS>);
527impl_float_host_operations!(IeeeFloat<SingleS>);
528impl_float_host_operations!(IeeeFloat<DoubleS>);
529
530#[derive(Debug, Clone, Copy)]
531pub enum HostUnaryFloatOp {
532    Sin,
533    Cos,
534    Exp,
535    Exp2,
536    Log,
537    Log10,
538    Log2,
539}
540
541pub fn host_unary_float_op<'tcx, S: Semantics>(
542    ecx: &mut MiriInterpCx<'tcx>,
543    f: &OpTy<'tcx>,
544    op: HostUnaryFloatOp,
545    dest: &PlaceTy<'tcx>,
546) -> InterpResult<'tcx>
547where
548    IeeeFloat<S>: HostFloatOperation + IeeeExt + Float + Into<Scalar>,
549{
550    use HostFloatOperation;
551
552    let f: IeeeFloat<S> = ecx.read_scalar(f)?.to_float()?;
553
554    // The fixed-value and clamping functions need the name as a string.
555    let name = match op {
556        HostUnaryFloatOp::Sin => "sin",
557        HostUnaryFloatOp::Cos => "cos",
558        HostUnaryFloatOp::Exp => "exp",
559        HostUnaryFloatOp::Exp2 => "exp2",
560        HostUnaryFloatOp::Log => "log",
561        HostUnaryFloatOp::Log10 => "log10",
562        HostUnaryFloatOp::Log2 => "log2",
563    };
564    let res = math::fixed_float_value(ecx, name, &[f]).unwrap_or_else(|| {
565        // Using host floats (but it's fine, these operations do not have
566        // guaranteed precision).
567        let res = match op {
568            HostUnaryFloatOp::Sin => f.host_sin(),
569            HostUnaryFloatOp::Cos => f.host_cos(),
570            HostUnaryFloatOp::Exp => f.host_exp(),
571            HostUnaryFloatOp::Exp2 => f.host_exp2(),
572            HostUnaryFloatOp::Log => f.host_log(),
573            HostUnaryFloatOp::Log10 => f.host_log10(),
574            HostUnaryFloatOp::Log2 => f.host_log2(),
575        };
576
577        // Apply a relative error of 4ULP to introduce some non-determinism
578        // simulating imprecise implementations and optimizations.
579        let res = math::apply_random_float_error_ulp(ecx, res, 4);
580
581        // Clamp the result to the guaranteed range of this function according to the C standard,
582        // if any.
583        math::clamp_float_value(name, res)
584    });
585
586    let res = ecx.adjust_nan(res, &[f]);
587    ecx.write_scalar(res, dest)?;
588    interp_ok(())
589}
590
591/// Extend functionality of `rustc_apfloat` softfloats for IEEE float types.
592pub trait IeeeExt: rustc_apfloat::Float {
593    // Some values we use:
594
595    #[inline]
596    fn one() -> Self {
597        Self::from_u128(1).value
598    }
599
600    #[inline]
601    fn two() -> Self {
602        Self::from_u128(2).value
603    }
604
605    #[inline]
606    fn three() -> Self {
607        Self::from_u128(3).value
608    }
609
610    fn pi() -> Self;
611
612    #[inline]
613    fn clamp(self, min: Self, max: Self) -> Self {
614        self.maximum(min).minimum(max)
615    }
616}
617
618macro_rules! impl_ieee_pi {
619    ($float_ty:ident, $semantic:ty) => {
620        impl IeeeExt for IeeeFloat<$semantic> {
621            #[inline]
622            fn pi() -> Self {
623                // We take the value from the standard library as the most reasonable source for an exact π here.
624                Self::from_bits(core::$float_ty::consts::PI.to_bits().into())
625            }
626        }
627    };
628}
629
630impl_ieee_pi!(f16, HalfS);
631impl_ieee_pi!(f32, SingleS);
632impl_ieee_pi!(f64, DoubleS);
633
634#[cfg(test)]
635mod tests {
636    use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS};
637
638    use super::sqrt;
639
640    #[test]
641    fn test_sqrt() {
642        #[track_caller]
643        fn test<S: rustc_apfloat::ieee::Semantics>(x: &str, expected: &str) {
644            let x: IeeeFloat<S> = x.parse().unwrap();
645            let expected: IeeeFloat<S> = expected.parse().unwrap();
646            let result = sqrt(x);
647            assert_eq!(result, expected);
648        }
649
650        fn exact_tests<S: rustc_apfloat::ieee::Semantics>() {
651            test::<S>("0", "0");
652            test::<S>("1", "1");
653            test::<S>("1.5625", "1.25");
654            test::<S>("2.25", "1.5");
655            test::<S>("4", "2");
656            test::<S>("5.0625", "2.25");
657            test::<S>("9", "3");
658            test::<S>("16", "4");
659            test::<S>("25", "5");
660            test::<S>("36", "6");
661            test::<S>("49", "7");
662            test::<S>("64", "8");
663            test::<S>("81", "9");
664            test::<S>("100", "10");
665
666            test::<S>("0.5625", "0.75");
667            test::<S>("0.25", "0.5");
668            test::<S>("0.0625", "0.25");
669            test::<S>("0.00390625", "0.0625");
670        }
671
672        exact_tests::<HalfS>();
673        exact_tests::<SingleS>();
674        exact_tests::<DoubleS>();
675        exact_tests::<QuadS>();
676
677        test::<SingleS>("2", "1.4142135");
678        test::<DoubleS>("2", "1.4142135623730951");
679
680        test::<SingleS>("1.1", "1.0488088");
681        test::<DoubleS>("1.1", "1.0488088481701516");
682
683        test::<SingleS>("2.2", "1.4832398");
684        test::<DoubleS>("2.2", "1.4832396974191326");
685
686        test::<SingleS>("1.22101e-40", "1.10499205e-20");
687        test::<DoubleS>("1.22101e-310", "1.1049932126488395e-155");
688
689        test::<SingleS>("3.4028235e38", "1.8446743e19");
690        test::<DoubleS>("1.7976931348623157e308", "1.3407807929942596e154");
691    }
692}