Skip to main content

declare_nums

Macro declare_nums 

Source
macro_rules! declare_nums {
    {$t: ident} => { ... };
    {@literal $t:ident} => { ... };
    (@constant $t:ident) => { ... };
    (@special $t:ident) => { ... };
}
Expand description

Declare commonly used num generics.

use num_lazy::declare_nums;
use num_traits::Float;
// Assign to generic type T.
// Important. Use the braces!
declare_nums!{T}
// Or declare as needed
// declare_nums!{@literal T}
// declare_nums!{@constant T}
// declare_nums!{@special T}

fn add_tiny<T: Float>(a: T) -> T {
    let tiny = five!() * epsilon!();
    a + tiny
}

fn main() {
    assert!(add_tiny(1.0_f64) == 1.000000000000001);
    assert!(add_tiny(1.0_f32) == 1.0000006);
}

Using declare_nums!{T} will populate the module with all available macros:

  • num!($n): equivalent to $t::from($n).unwrap(), where $t is the generic type identifier you declared, and $n is any expression evaluated to a number.
  • Literals as in declare_nums!{@literal T}.
  • Constants as in declare_nums!{@constant T}.
  • Special as in declare_nums!{@special T}.

Each match arm will populate the module with:

  • Literals: declare_nums!{@literal T}
    • zero!() to ten!()
    • hundred!(), thousand!(), and million!()
    • half!(), third!(), and quarter!()
    • tenth!(), hundredth!(), thousandth!(), and millionth!()
  • Constants: declare_nums!{@constant T}
    • pi!(), pi_2!(), pi_3!(), frac_1_pi!(), frac_2_pi!(), and frac_2_sqrt_pi!()
    • tau!()
    • e!()
    • ln_2!(), ln_10!(), log2_10!(), log2_e!(), log10_2!(), and log10_e!()
    • sqrt_2!() and frac_1_sqrt_2!()
    • The golden ratio: phi!()
  • Special Constants: declare_nums!{@special T}
    • Infinity: inf!() and neg_inf!()
    • nan!()
    • Min/max type representation value: min_val!(), max_val!(), and min_positive!()
    • Machine epsilon: epsilon!()
    • Negative zero: neg_zero!()