SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
C++ Expression Template
: y x
!!
double x = 1.0;
double y = 3.0 * x + 2.0;
double dydx = derivative(y) // ?
4 2 y
4 (Expression Template)
Expression Template
4
4 GOF Composite
4
4
4 2 !!
: <operator, 1, 2>
struct add_op {}; struct sub_op {}; struct mul_op {}; struct div_op {};
template<typename OP, typename E1, typename E2>
class binary_expression {
public:
binary_expression(const E1& e1, const E2& e2)
: _e1(e1), _e2(e2){
}
const E1& e1() const {return _e1;}
const E2& e2() const {return _e2;}
private:
const E1 _e1;
const E2 _e2;
};
class Variable {
public:
Variable(const double x): _x(x) {}
double get() const {return _x;}
private:
const double _x;
};
:
template<typename E1, typename E2>
auto operator +(const E1& x, const E2& y) {
return binary_expression<add_op, E1, E2>(x, y);
};
template<typename E1, typename E2>
auto operator -(const E1& x, const E2& y) {
return binary_expression<sub_op, E1, E2>(x, y);
};
template<typename E1, typename E2>
auto operator *(const E1& x, const E2& y) {
return binary_expression<mul_op, E1, E2>(x, y);
};
template<typename E1, typename E2>
auto operator /(const E1& x, const E2& y) {
return binary_expression<div_op, E1, E2>(x, y);
};
int main() {
auto x = Variable(1.0);
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
auto y2 = y1 * y0;
std::cout << typeid(y0).name() << std::endl;
std::cout << typeid(y1).name() << std::endl;
std::cout << typeid(y2).name() << std::endl;
}
4
code
auto y0 = x + 2.0;
std::cout << typeid(y0).name() << std::endl;
output
binary_expression<add_op, Variable, double>
code
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
std::cout << typeid(y1).name() << std::endl;
output
binary_expression<
add_op,
binary_expression<
mul_op, double, binary_expression<add_op, Variable, double>
>,
double
>
code
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
auto y2 = y1 * y0;
std::cout << typeid(y2).name() << std::endl;
output
binary_expression<
mul_op,
binary_expression<
add_op,
binary_expression<mul_op, double, binary_expression<add_op, Variable, double> >,
double
>,
binary_expression<add_op, Variable, double>
>
: !
auto eval(const Variable& e) {return e.get();}
auto eval(const double e) {return e;}
template<typename E1, typename E2>
auto eval(const binary_expression<add_op, E1, E2>& e) {
return eval(e.e1()) + eval(e.e2());
}
template<typename E1, typename E2>
auto eval(const binary_expression<mul_op, E1, E2>& e) {
return eval(e.e1()) * eval(e.e2());
}
code
auto x = Variable(1.0);
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
auto y2 = y1 * y0;
std::cout << eval(y2) << std::endl;
output
42
: eval
auto diff(const double e) {return 0;}
auto diff(const Variable& e) {return 1;}
template<typename E1, typename E2>
auto diff(const binary_expression<add_op, E1, E2>& e) {
// x + y -> dx + dy
return diff(e.e1()) + diff(e.e2());
}
template<typename E1, typename E2>
auto diff(const binary_expression<mul_op, E1, E2>& e) {
// x * y -> dx * y + x * dy
return diff(e.e1()) * eval(e.e2()) + eval(e.e1()) * diff(e.e2());
}
code
auto x = Variable(1.0);
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
auto y2 = y1 * y0;
std::cout << diff(y0) << std::endl;
std::cout << diff(y1) << std::endl;
std::cout << diff(y2) << std::endl;
output
1
3
23
!
!!
auto x = Variable(1.0);
auto y = 3.0 * x * x + 2.0 * x;
auto dydx = derivative(y)
std::cout << typeid(dydx).name() << std::endl;
y
// 6.0 * x + 2.0
binary_expression<
add_op,
binary_expression<mul_op, double, Variable>,
double
>
class one {};
class zero {};
auto derivative(const double e) {return zero();}
auto derivative(const Variable& e) {return one();}
template<typename E1, typename E2>
auto derivative(const binary_expression<add_op, E1, E2>& e) {
return derivative(e.e1()) + derivative(e.e2());
}
template<typename E1, typename E2>
auto derivative(const binary_expression<mul_op, E1, E2>& e) {
return e.e1() * derivative(e.e2()) + derivative(e.e1()) * e.e2();
}
code
auto x = Variable(1.0);
auto y0 = x + 2.0;
std::cout << typeid(y0).name() << std::endl;
output
binary_expression<add_op, one, zero>
code
auto x = Variable(1.0);
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
std::cout << typeid(y1).name() << std::endl;
output
binary_expression<
add_op,
binary_expression<
add_op,
binary_expression<
mul_op,
double,
binary_expression<add_op, one, zero>
>,
binary_expression<
mul_op,
zero,
binary_expression<add_op, Variable, double>
>
>,
zero
>
!
: !
4 a + 0 = a
template <typename E>
auto operator +(const E& e, const zero&) {return e;}
template <typename E>
auto operator +(const zero&, const E& e) {return e;}
template <typename E>
auto operator *(const E& e, const zero&) {return zero();}
template <typename E>
auto operator *(const zero&, const E& e) {return zero();}
template <typename E>
auto operator *(const E& e, const one&) {return e;}
template <typename E>
auto operator *(const one&, const E& e) {return e;}
code
auto x = Variable(1.0);
auto y0 = x + 2.0;
std::cout << typeid(y0).name() << std::endl;
output! one !
one
code
auto x = Variable(1.0);
auto y0 = x + 2.0;
auto y1 = 3.0 * y0 + 5.0;
std::cout << typeid(y1).name() << std::endl;
output!! double !!
double
4
4 Expression Template ( )
&

Mais conteúdo relacionado

Mais procurados

C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st StudyChris Ohk
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java starsMatteo Bonifazi
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nmmohamed sikander
 
C tech questions
C tech questionsC tech questions
C tech questionsvijay00791
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programmingPrabhu Govind
 
SPL 10.1 | Manual Tracing on Basic Loop & 1D Array
SPL 10.1 | Manual Tracing on Basic Loop & 1D ArraySPL 10.1 | Manual Tracing on Basic Loop & 1D Array
SPL 10.1 | Manual Tracing on Basic Loop & 1D ArrayMohammad Imam Hossain
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacionJeff Tu Pechito
 
C++ Question on References and Function Overloading
C++ Question on References and Function OverloadingC++ Question on References and Function Overloading
C++ Question on References and Function Overloadingmohamed sikander
 
Assignement of c++
Assignement of c++Assignement of c++
Assignement of c++Syed Umair
 
Assignement of programming & problem solving u.s ass.(1)
Assignement of programming & problem solving u.s ass.(1)Assignement of programming & problem solving u.s ass.(1)
Assignement of programming & problem solving u.s ass.(1)Syed Umair
 
C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2Rumman Ansari
 
Inteligencia artificial 4
Inteligencia artificial 4Inteligencia artificial 4
Inteligencia artificial 4Nauber Gois
 

Mais procurados (20)

C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java stars
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nm
 
Pointers
PointersPointers
Pointers
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Array notes
Array notesArray notes
Array notes
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programming
 
SPL 10.1 | Manual Tracing on Basic Loop & 1D Array
SPL 10.1 | Manual Tracing on Basic Loop & 1D ArraySPL 10.1 | Manual Tracing on Basic Loop & 1D Array
SPL 10.1 | Manual Tracing on Basic Loop & 1D Array
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
 
Qno 1 (e)
Qno 1 (e)Qno 1 (e)
Qno 1 (e)
 
C++ Question on References and Function Overloading
C++ Question on References and Function OverloadingC++ Question on References and Function Overloading
C++ Question on References and Function Overloading
 
Assignement of c++
Assignement of c++Assignement of c++
Assignement of c++
 
Program presentation
Program presentationProgram presentation
Program presentation
 
Implementing stack
Implementing stackImplementing stack
Implementing stack
 
pointers 1
pointers 1pointers 1
pointers 1
 
MFC Polygon
MFC PolygonMFC Polygon
MFC Polygon
 
Assignement of programming & problem solving u.s ass.(1)
Assignement of programming & problem solving u.s ass.(1)Assignement of programming & problem solving u.s ass.(1)
Assignement of programming & problem solving u.s ass.(1)
 
C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2C Programming Language Step by Step Part 2
C Programming Language Step by Step Part 2
 
Inteligencia artificial 4
Inteligencia artificial 4Inteligencia artificial 4
Inteligencia artificial 4
 

Semelhante a C++ Expression Templateを使って式をコンパイル時に微分

Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたAkira Maruoka
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency명신 김
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Make two classes called Points and Lines- Class points should have the.docx
Make two classes called Points and Lines- Class points should have the.docxMake two classes called Points and Lines- Class points should have the.docx
Make two classes called Points and Lines- Class points should have the.docxsngyun4t79
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogrammingMårten Rånge
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFTimur Safin
 

Semelhante a C++ Expression Templateを使って式をコンパイル時に微分 (20)

Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Make two classes called Points and Lines- Class points should have the.docx
Make two classes called Points and Lines- Class points should have the.docxMake two classes called Points and Lines- Class points should have the.docx
Make two classes called Points and Lines- Class points should have the.docx
 
Qno 1 (c)
Qno 1 (c)Qno 1 (c)
Qno 1 (c)
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
C++ TUTORIAL 9
C++ TUTORIAL 9C++ TUTORIAL 9
C++ TUTORIAL 9
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
L10
L10L10
L10
 
Clean code
Clean codeClean code
Clean code
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogramming
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoF
 

Último

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Último (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

C++ Expression Templateを使って式をコンパイル時に微分

  • 2. : y x !! double x = 1.0; double y = 3.0 * x + 2.0; double dydx = derivative(y) // ? 4 2 y 4 (Expression Template)
  • 3. Expression Template 4 4 GOF Composite 4 4 4 2 !!
  • 4. : <operator, 1, 2> struct add_op {}; struct sub_op {}; struct mul_op {}; struct div_op {}; template<typename OP, typename E1, typename E2> class binary_expression { public: binary_expression(const E1& e1, const E2& e2) : _e1(e1), _e2(e2){ } const E1& e1() const {return _e1;} const E2& e2() const {return _e2;} private: const E1 _e1; const E2 _e2; }; class Variable { public: Variable(const double x): _x(x) {} double get() const {return _x;} private: const double _x; };
  • 5. : template<typename E1, typename E2> auto operator +(const E1& x, const E2& y) { return binary_expression<add_op, E1, E2>(x, y); }; template<typename E1, typename E2> auto operator -(const E1& x, const E2& y) { return binary_expression<sub_op, E1, E2>(x, y); }; template<typename E1, typename E2> auto operator *(const E1& x, const E2& y) { return binary_expression<mul_op, E1, E2>(x, y); }; template<typename E1, typename E2> auto operator /(const E1& x, const E2& y) { return binary_expression<div_op, E1, E2>(x, y); };
  • 6. int main() { auto x = Variable(1.0); auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; auto y2 = y1 * y0; std::cout << typeid(y0).name() << std::endl; std::cout << typeid(y1).name() << std::endl; std::cout << typeid(y2).name() << std::endl; } 4
  • 7. code auto y0 = x + 2.0; std::cout << typeid(y0).name() << std::endl; output binary_expression<add_op, Variable, double>
  • 8. code auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; std::cout << typeid(y1).name() << std::endl; output binary_expression< add_op, binary_expression< mul_op, double, binary_expression<add_op, Variable, double> >, double >
  • 9. code auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; auto y2 = y1 * y0; std::cout << typeid(y2).name() << std::endl; output binary_expression< mul_op, binary_expression< add_op, binary_expression<mul_op, double, binary_expression<add_op, Variable, double> >, double >, binary_expression<add_op, Variable, double> >
  • 10. : ! auto eval(const Variable& e) {return e.get();} auto eval(const double e) {return e;} template<typename E1, typename E2> auto eval(const binary_expression<add_op, E1, E2>& e) { return eval(e.e1()) + eval(e.e2()); } template<typename E1, typename E2> auto eval(const binary_expression<mul_op, E1, E2>& e) { return eval(e.e1()) * eval(e.e2()); }
  • 11. code auto x = Variable(1.0); auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; auto y2 = y1 * y0; std::cout << eval(y2) << std::endl; output 42
  • 12. : eval auto diff(const double e) {return 0;} auto diff(const Variable& e) {return 1;} template<typename E1, typename E2> auto diff(const binary_expression<add_op, E1, E2>& e) { // x + y -> dx + dy return diff(e.e1()) + diff(e.e2()); } template<typename E1, typename E2> auto diff(const binary_expression<mul_op, E1, E2>& e) { // x * y -> dx * y + x * dy return diff(e.e1()) * eval(e.e2()) + eval(e.e1()) * diff(e.e2()); }
  • 13. code auto x = Variable(1.0); auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; auto y2 = y1 * y0; std::cout << diff(y0) << std::endl; std::cout << diff(y1) << std::endl; std::cout << diff(y2) << std::endl; output 1 3 23
  • 14. ! !!
  • 15. auto x = Variable(1.0); auto y = 3.0 * x * x + 2.0 * x; auto dydx = derivative(y) std::cout << typeid(dydx).name() << std::endl; y // 6.0 * x + 2.0 binary_expression< add_op, binary_expression<mul_op, double, Variable>, double >
  • 16. class one {}; class zero {}; auto derivative(const double e) {return zero();} auto derivative(const Variable& e) {return one();} template<typename E1, typename E2> auto derivative(const binary_expression<add_op, E1, E2>& e) { return derivative(e.e1()) + derivative(e.e2()); } template<typename E1, typename E2> auto derivative(const binary_expression<mul_op, E1, E2>& e) { return e.e1() * derivative(e.e2()) + derivative(e.e1()) * e.e2(); }
  • 17. code auto x = Variable(1.0); auto y0 = x + 2.0; std::cout << typeid(y0).name() << std::endl; output binary_expression<add_op, one, zero>
  • 18. code auto x = Variable(1.0); auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; std::cout << typeid(y1).name() << std::endl; output binary_expression< add_op, binary_expression< add_op, binary_expression< mul_op, double, binary_expression<add_op, one, zero> >, binary_expression< mul_op, zero, binary_expression<add_op, Variable, double> > >, zero >
  • 19. !
  • 20. : ! 4 a + 0 = a template <typename E> auto operator +(const E& e, const zero&) {return e;} template <typename E> auto operator +(const zero&, const E& e) {return e;} template <typename E> auto operator *(const E& e, const zero&) {return zero();} template <typename E> auto operator *(const zero&, const E& e) {return zero();} template <typename E> auto operator *(const E& e, const one&) {return e;} template <typename E> auto operator *(const one&, const E& e) {return e;}
  • 21. code auto x = Variable(1.0); auto y0 = x + 2.0; std::cout << typeid(y0).name() << std::endl; output! one ! one
  • 22. code auto x = Variable(1.0); auto y0 = x + 2.0; auto y1 = 3.0 * y0 + 5.0; std::cout << typeid(y1).name() << std::endl; output!! double !! double