hyperopt/traits/
constants.rs

1//! Constants used in the algorithms and kernels.
2//!
3//! Some constants are missing in [`num_traits`] and/or the standard library.
4//! Some _are_ available, but only through [`num_traits::Float`], which is not implemented
5//! for certain types. All in all, it was easier to go this way.
6
7#![allow(clippy::excessive_precision, clippy::unreadable_literal)]
8
9macro_rules! define_trait {
10    ($trait_:ident, $ident:ident, $value:literal, $comment:literal) => {
11        #[doc = $comment]
12        pub trait $trait_ {
13            const $ident: Self;
14        }
15
16        impl $trait_ for f32 {
17            const $ident: Self = $value;
18        }
19
20        impl $trait_ for f64 {
21            const $ident: Self = $value;
22        }
23
24        #[cfg(feature = "ordered-float")]
25        impl_for_ordered_float!($trait_, $ident);
26    };
27}
28
29macro_rules! impl_for_ordered_float {
30    ($trait_:ident, $ident:ident) => {
31        impl $trait_ for ordered_float::NotNan<f32> {
32            const $ident: Self = unsafe { Self::new_unchecked(f32::$ident) };
33        }
34
35        impl $trait_ for ordered_float::NotNan<f64> {
36            const $ident: Self = unsafe { Self::new_unchecked(f64::$ident) };
37        }
38
39        impl $trait_ for ordered_float::OrderedFloat<f32> {
40            const $ident: Self = Self(f32::$ident);
41        }
42
43        impl $trait_ for ordered_float::OrderedFloat<f64> {
44            const $ident: Self = Self(f64::$ident);
45        }
46    };
47}
48
49define_trait!(
50    ConstSqrt3,
51    SQRT_3,
52    1.7320508075688772935274463415058723669428052538103806280558069794,
53    "√3"
54);
55define_trait!(
56    ConstSqrt5,
57    SQRT_5,
58    2.2360679774997896964091736687312762354406183596115257242708972454,
59    "√5"
60);
61define_trait!(
62    ConstDoubleSqrt3,
63    DOUBLE_SQRT_3,
64    3.4641016151377545870548926830117447338856105076207612561116139589,
65    "2√3"
66);
67define_trait!(
68    ConstFrac1SqrtTau,
69    FRAC_1_SQRT_TAU,
70    0.3989422804014326779399460599343818684758586311649346576659258296,
71    "1 / √(2π)"
72);
73define_trait!(ConstThreeQuarters, THREE_QUARTERS, 0.75, "`0.75`");
74define_trait!(ConstOneHalf, ONE_HALF, 0.5, "`0.5`");