Created
April 27, 2014 02:08
-
-
Save yuriks/11336079 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::num::{One, Zero, one, zero}; | |
| #[deriving(Eq)] | |
| struct Dual<T> { x: T, dx: T } | |
| impl<T: Zero> Zero for Dual<T> { | |
| fn zero() -> Dual<T> { | |
| Dual { x: zero(), dx: zero() } | |
| } | |
| fn is_zero(&self) -> bool { | |
| self.x.is_zero() && self.dx.is_zero() | |
| } | |
| } | |
| impl<T: One + Zero> One for Dual<T> { | |
| fn one() -> Dual<T> { | |
| Dual { x: one(), dx: zero() } | |
| } | |
| } | |
| impl<T: Add<T,T>> Add<Dual<T>, Dual<T>> for Dual<T> { | |
| fn add(&self, rhs: &Dual<T>) -> Dual<T> { | |
| Dual { | |
| x: self.x + rhs.x, | |
| dx: self.dx + rhs.dx | |
| } | |
| } | |
| } | |
| impl<T: Sub<T,T>> Sub<Dual<T>, Dual<T>> for Dual<T> { | |
| fn sub(&self, rhs: &Dual<T>) -> Dual<T> { | |
| Dual { | |
| x: self.x - rhs.x, | |
| dx: self.dx - rhs.dx | |
| } | |
| } | |
| } | |
| impl<T: Add<T,T> + Mul<T,T>> Mul<Dual<T>, Dual<T>> for Dual<T> { | |
| fn mul(&self, rhs: &Dual<T>) -> Dual<T> { | |
| Dual { | |
| x: self.x * rhs.x, | |
| dx: self.dx * rhs.x + self.x * rhs.dx | |
| } | |
| } | |
| } | |
| impl<T: Sub<T,T> + Mul<T,T> + Div<T,T>> Div<Dual<T>, Dual<T>> for Dual<T> { | |
| fn div(&self, rhs: &Dual<T>) -> Dual<T> { | |
| Dual { | |
| x: self.x / rhs.x, | |
| dx: (self.dx * rhs.x - self.x * rhs.dx) / (rhs.x * rhs.x) | |
| } | |
| } | |
| } | |
| fn main() { | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment