Skip to main content

num_dual/datatypes/
real.rs

1use crate::{DualNum, DualNumFloat, DualStruct};
2use num_traits::{FloatConst, FromPrimitive, Inv, Num, One, Signed, Zero};
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5use std::fmt;
6use std::iter::{Product, Sum};
7use std::ops::{
8    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
9};
10
11/// A real number for the calculations of zeroth derivatives in generic contexts.
12///
13/// In most situations f64 or f32 can be used directly!
14#[derive(Copy, Clone, Debug)]
15#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
16pub struct Real<T> {
17    /// Real part of the dual number
18    pub re: T,
19}
20
21#[cfg(feature = "ndarray")]
22impl<T: DualNum> ndarray::ScalarOperand for Real<T> {}
23
24impl<T> Real<T> {
25    /// Create a new dual number from its fields.
26    #[inline]
27    pub fn new(re: T) -> Self {
28        Self { re }
29    }
30}
31
32impl<T> Real<T> {
33    /// Create a new dual number from the real part.
34    #[inline]
35    pub fn from_re(re: T) -> Self {
36        Self::new(re)
37    }
38}
39
40/* chain rule */
41impl<T> Real<T> {
42    #[inline]
43    fn chain_rule(&self, f0: T) -> Self {
44        Self::new(f0)
45    }
46}
47
48/* product rule */
49impl<T: DualNum> Mul<&Real<T>> for &Real<T> {
50    type Output = Real<T>;
51    #[inline]
52    fn mul(self, other: &Real<T>) -> Self::Output {
53        Real::new(self.re.clone() * other.re.clone())
54    }
55}
56
57/* quotient rule */
58impl<T: DualNum> Div<&Real<T>> for &Real<T> {
59    type Output = Real<T>;
60    #[inline]
61    #[expect(clippy::suspicious_arithmetic_impl)]
62    fn div(self, other: &Real<T>) -> Real<T> {
63        let inv = other.re.recip();
64        Real::new(self.re.clone() * inv.clone())
65    }
66}
67
68/* string conversions */
69impl<T: DualNum> fmt::Display for Real<T> {
70    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71        fmt::Display::fmt(&self.re, f)
72    }
73}
74
75impl_zeroth_derivatives!(Real, []);
76impl_dual!(Real, []);
77#[cfg(feature = "nalgebra")]
78impl_nalgebra!(Real, []);