Created
February 23, 2017 20:01
-
-
Save nikhedonia/ef97574e2fa8afce59cfbe5c1bb1ccde to your computer and use it in GitHub Desktop.
example showing the beauty of duals
This file contains 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
// Example program | |
#include <iostream> | |
#include <string> | |
struct Dual { | |
float real; | |
float img; | |
Dual(float x, float y=0) | |
:real{x}, img{y} | |
{} | |
}; | |
Dual operator+(Dual l, Dual r) { | |
return { | |
l.real+r.real, | |
l.img +r.img | |
}; | |
} | |
Dual operator*(Dual l, Dual r) { | |
return { | |
l.real*r.real, | |
l.img * r.real + l.real * r.img | |
}; | |
} | |
std::ostream& operator<< (std::ostream& o, Dual x) { | |
return o << "("<<x.real << "|" <<x.img<<")"; | |
} | |
auto f(auto x) { | |
return x*x + 2*x + 3; | |
} | |
auto df(auto x) { | |
return 2*x + 2; | |
} | |
static Dual d = {0,1}; | |
int main() { | |
std::cout << "manual (f(3)|df(3)) = (" << f(3) << "|" << df(3) <<")"<< std::endl; | |
std::cout << "using duals : (f(3)|df(3)) = " << f( 3 + 1*d ) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment