peroxide/traits/
num.rs

1//! Missing operations & comprehensive number structures
2//!
3//! ## `Real` trait
4//!
5//! * `Real` is a trait for binding `f64`, `AD`
6//! * `Real` requires `PowOps, TrigOps, ExpLogOps` & `std::Ops<Self>` & `std::Ops<f64>`
7//!
8//!     ```rust
9//!     extern crate peroxide;
10//!     use peroxide::fuga::*;
11//!
12//!     fn main() {
13//!         let x_f64 = 2f64;
14//!         let x_ad1 = AD1(2f64,1f64);
15//!         let x_ad2 = AD2(2f64, 1f64, 0f64);
16//!
17//!         f(x_f64).print();
18//!         f(x_ad1).print();
19//!         f(x_ad2).print();
20//!     }
21//!
22//!     fn f<T: Real>(x: T) -> T {
23//!         return x.powi(2)
24//!     }
25//!     ```
26
27use crate::structure::ad::AD;
28use peroxide_num::{ExpLogOps, PowOps, TrigOps};
29use std::ops::{Add, Div, Mul, Neg, Sub};
30
31pub trait Real:
32    PowOps
33    + TrigOps
34    + ExpLogOps
35    + Neg
36    + PartialOrd
37    + Add<Output = Self>
38    + Mul<Output = Self>
39    + Div<Output = Self>
40    + Sub<Output = Self>
41    + Add<f64, Output = Self>
42    + Mul<f64, Output = Self>
43    + Div<f64, Output = Self>
44    + Sub<f64, Output = Self>
45    + Clone
46    + Copy
47{
48    fn to_f64(&self) -> f64;
49    fn from_f64(f: f64) -> Self;
50    fn to_ad(&self) -> AD;
51}
52
53impl Real for f64 {
54    fn to_f64(&self) -> f64 {
55        *self
56    }
57
58    fn from_f64(f: f64) -> Self {
59        f
60    }
61
62    fn to_ad(&self) -> AD {
63        AD::from(*self)
64    }
65}
66
67impl Real for AD {
68    fn to_f64(&self) -> f64 {
69        self.x()
70    }
71
72    fn from_f64(f: f64) -> Self {
73        AD::from(f)
74    }
75
76    fn to_ad(&self) -> AD {
77        *self
78    }
79}