mathru/elementary/exponential.rs
1use crate::algebra::abstr::{Complex, Real, Sign};
2use std::{f32, f64};
3
4/// Exponential function and its inverse
5///
6///<https://en.wikipedia.org/wiki/Exponential_function>
7pub trait Exponential {
8 /// Euler's number
9 fn e() -> Self;
10
11 ///Exponential function
12 fn exp(self) -> Self;
13
14 /// Natural logarithm function
15 fn ln(self) -> Self;
16}
17
18macro_rules! exponential_impl {
19 ($t:ty, $e: expr) => {
20 impl Exponential for $t {
21 fn e() -> Self {
22 $e
23 }
24
25 ///Exponential function
26 fn exp(self) -> Self {
27 self.exp()
28 }
29
30 ///Logarithm function
31 fn ln(self) -> Self {
32 self.ln()
33 }
34 }
35 };
36}
37
38exponential_impl!(f32, f32::consts::E);
39exponential_impl!(f64, f64::consts::E);
40
41impl<T> Exponential for Complex<T>
42where
43 T: Real,
44{
45 /// Returns the euler number represented as a complex number
46 fn e() -> Self {
47 Complex {
48 re: T::e(),
49 im: T::zero(),
50 }
51 }
52
53 ///Exponential function
54 ///
55 /// # Example
56 ///
57 /// ```
58 /// use mathru::{elementary::Exponential};
59 /// use mathru::algebra::abstr::Complex;
60 ///
61 /// let z: Complex<f64> = Complex::new(1.0, 2.0);
62 /// let a: Complex<f64> = z.exp();
63 /// ```
64 fn exp(self) -> Self {
65 let k: T = self.re.exp();
66 Complex {
67 re: k * self.im.cos(),
68 im: k * self.im.sin(),
69 }
70 }
71
72 ///Logiarithm function
73 ///
74 /// # Example
75 ///
76 /// ```
77 /// use mathru::{elementary::Exponential};
78 /// use mathru::algebra::abstr::Complex;
79 ///
80 /// let a: Complex<f64> = Complex::new(1.0_f64, 2.0_f64);
81 /// let refer: Complex<f64> = Complex::new(5.0_f64.powf(0.5_f64).ln(), 2.0_f64.atan());
82 ///
83 /// assert_eq!(refer, a.ln());
84 /// ```
85 fn ln(self) -> Self {
86 Complex {
87 re: self.abs().re.ln(),
88 im: self.arg().re,
89 }
90 }
91}