dfo/forward/
traits.rs

1/// Trait for any number-like structure that implements
2/// automatic foward differentiation.
3///
4/// A variable should start with unit derivative, and
5/// a constant should have a zero derivative.
6///
7/// # Examples
8///
9/// ```
10/// # use dfo::forward::primitive::*;
11/// let x = DFloat32::var(14.0);
12///
13/// assert_eq!(*x.value(), 14.0);
14/// assert_eq!(*x.deriv(),  1.0);
15///
16/// let c = DFloat32::cst(3.14);
17///
18/// assert_eq!(*c.value(), 3.14);
19/// assert_eq!(*c.deriv(),  0.0);
20///
21/// let y = c * x * x; // y = c * x^2
22///
23/// assert_eq!(*y.deriv(), 2.0 * 3.14 * 14.0);
24/// ```
25pub trait Differentiable {
26    /// Inner type, that can be used to construct
27    /// a new differentiable variable of constant.
28    type Inner;
29    /// Creates a new variable, whose derivative will
30    /// propagate.
31    fn var(x: Self::Inner) -> Self;
32    /// Creates a new constant, whose derivative will
33    /// not propagate, since a constant has a zero derivative.
34    fn cst(x: Self::Inner) -> Self;
35    /// Returns the inner value of this number.
36    ///
37    /// Usually, this is the same value as if no derivative were
38    /// ever computed.
39    fn value(&self) -> &Self::Inner;
40    /// Returns the derivative of this number.
41    fn deriv(&self) -> &Self::Inner;
42    /// Creates a new number from tuple.
43    fn from_tuple(x: Self::Inner, dx: Self::Inner) -> Self;
44    /// Destructures self into a tuple.
45    fn into_tuple(self) -> (Self::Inner, Self::Inner);
46}