-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdifferentiator.cpp
More file actions
90 lines (87 loc) · 3.05 KB
/
Copy pathdifferentiator.cpp
File metadata and controls
90 lines (87 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "differentiator.h"
#include <stdexcept>
std::unique_ptr<Expr> differentiate(const Expr* e, const std::string& var){
if(dynamic_cast<const NumberExpr*>(e)){
return std::make_unique<NumberExpr>(0);
}
if(auto v=dynamic_cast<const VariableExpr*>(e)){
return std::make_unique<NumberExpr>(v->name == var ? 1 : 0);
}
if(auto bin=dynamic_cast<const BinaryExpr*>(e)){
char op = bin->op;
if(op == '+'){
return std::make_unique<BinaryExpr>(
'+',
differentiate(bin->left.get(), var),
differentiate(bin->right.get(), var)
);
}
if(op == '-'){
return std::make_unique<BinaryExpr>(
'-',
differentiate(bin->left.get(), var),
differentiate(bin->right.get(), var)
);
}
if(op == '*'){
// (u * v)' = u'v + uv'
return std::make_unique<BinaryExpr>(
'+',
std::make_unique<BinaryExpr>(
'*',
differentiate(bin->left.get(), var),
bin->right->clone()
),
std::make_unique<BinaryExpr>(
'*',
bin->left->clone(),
differentiate(bin->right.get(), var)
)
);
}
if(op == '/'){
// (u / v)' = (u'v - uv') / v^2
return std::make_unique<BinaryExpr>(
'/',
std::make_unique<BinaryExpr>(
'-',
std::make_unique<BinaryExpr>(
'*',
differentiate(bin->left.get(), var),
bin->right->clone()
),
std::make_unique<BinaryExpr>(
'*',
bin->left->clone(),
differentiate(bin->right.get(), var)
)
),
std::make_unique<BinaryExpr>(
'^',
bin->right->clone(),
std::make_unique<NumberExpr>(2)
)
);
}
if(op == '^'){
if(auto exponent = dynamic_cast<NumberExpr*>(bin->right.get())){
double n = exponent->value;
return std::make_unique<BinaryExpr>(
'*',
std::make_unique<BinaryExpr>(
'*',
std::make_unique<NumberExpr>(n),
std::make_unique<BinaryExpr>(
'^',
bin->left->clone(),
std::make_unique<NumberExpr>(n-1)
)
),
differentiate(bin->left.get(), var)
);
}
throw std::runtime_error("Non-numeric exponents not supported yet");
}
}
throw std::runtime_error("Unknown expression type in differentiate");
}