tpt_math_numeric/lib.rs
1#![no_std]
2//! Scalar numeric trait glue for the `tpt-math` substrate.
3//!
4//! This crate is a thin wrapper over [`num_traits`] (and, when the `libm`
5//! feature is enabled, [`libm`]) that re-exports the numeric traits the rest
6//! of `tpt-math` builds on, and provides a single [`Scalar`] supertrait that
7//! captures "a floating-point scalar type we can do math on".
8//!
9//! # Features
10//!
11//! * `std` (default) — enable [`num_traits`]' `std`-dependent items.
12//! * `alloc` — signal that an allocator is available (no extra deps).
13//! * `libm` — re-export [`libm`] so callers can do transcendental math in
14//! `no_std` environments.
15//!
16//! [`num_traits`]: num_traits
17//! [`libm`]: libm
18
19#[cfg(feature = "alloc")]
20extern crate alloc;
21
22pub mod ode;
23pub mod quadrature;
24pub mod report;
25pub mod roots;
26#[cfg(feature = "alloc")]
27pub mod sensitivity;
28pub mod stiff;
29
30pub use report::{SolveReport, SolveStatus};
31
32pub use num_traits::{
33 cast, float::FloatConst, real::Real, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg,
34 CheckedRem, CheckedShl, CheckedShr, CheckedSub, Float, FromPrimitive, Inv, Num, NumAssign,
35 NumAssignOps, NumCast, NumOps, One, Pow, PrimInt, Signed, ToPrimitive, Unsigned, Zero,
36};
37
38pub use num_traits;
39
40#[cfg(feature = "libm")]
41pub use libm;
42
43/// A floating-point scalar type usable throughout `tpt-math`.
44///
45/// This is a convenience supertrait: anything that is a [`Float`], can be
46/// constructed from/cast to primitive floats via [`NumCast`], and carries the
47/// mathematical constants from [`FloatConst`] satisfies it.
48///
49/// # Examples
50///
51/// ```
52/// use tpt_math_numeric::Scalar;
53///
54/// fn midpoint<T: Scalar>(a: T, b: T) -> T {
55/// (a + b) / (T::one() + T::one())
56/// }
57///
58/// assert_eq!(midpoint(2.0_f64, 4.0_f64), 3.0_f64);
59/// ```
60pub trait Scalar: Float + NumCast + FloatConst {}
61impl<T: Float + NumCast + FloatConst> Scalar for T {}
62
63/// Re-export of the [`Num`]/`Float` numeric hierarchy root for convenience.
64pub mod prelude {
65 pub use crate::{Float, FloatConst, Num, NumCast, One, Real, Scalar, Signed, Unsigned, Zero};
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 #[test]
73 fn scalar_is_implemented_for_f64() {
74 fn takes_scalar<T: Scalar>(_: T) {}
75 takes_scalar(1.0_f64);
76 takes_scalar(1.0_f32);
77 }
78
79 #[test]
80 fn constants_are_available() {
81 assert!((f64::E() - core::f64::consts::E).abs() < 1e-12);
82 assert!((f64::PI() - core::f64::consts::PI).abs() < 1e-12);
83 }
84
85 #[test]
86 fn cast_roundtrip() {
87 let x: f64 = 3.5;
88 let y: i64 = NumCast::from(x).unwrap();
89 assert_eq!(y, 3);
90 }
91}