-
Notifications
You must be signed in to change notification settings - Fork 0
/
test1.cpp
139 lines (130 loc) · 3.01 KB
/
test1.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <cmath>
#include <stdexcept>
#include <string>
using namespace std;
class Constant : public Function
{
public:
static Constant *create(const double &val)
{
return new Constant(val);
}
Function *differential() override
{
// (c)' = 0
return new Constant(0);
}
double eval(double _val) override
{
return val;
}
private:
Constant(const double &_val) : val(_val) {}
double val;
};
class Variable : public Function
{
public:
static Variable *create(const string &var)
{
return new Variable(var);
}
Function *differential() override
{
//(x)' = 1
return Constant::create(1);
}
double eval(double val) override
{
return val;
}
private:
Variable(const string &_var) : var(_var) {}
string var;
};
class Polynomial : public Function
{
public:
static Polynomial *create(Function *base, Function *exp)
{
return new Polynomial(base, exp);
}
Function *differential() override;
double eval(double val) override
{
return pow(base->eval(val), exp->eval(val));
}
private:
Polynomial(Function *_base, Function *_exp) : base(_base), exp(_exp) {}
Function *base;
Function *exp;
};
class Arithmetic : public Function
{
public:
static Arithmetic *create(Function *l, char op, Function *r)
{
switch (op)
{
case '+':
return new Arithmetic(Type::Add, l, r);
case '-':
return new Arithmetic(Type::Sub, l, r);
case '*':
return new Arithmetic(Type::Mul, l, r);
}
}
Function *differential() override
{
Function *dl = l->differential(), *dr = r->differential();
switch (type)
{
// (A+B)' = A' + B', (A-B)' = A' - B'
case Type::Add:
case Type::Sub:
return new Arithmetic(type, dl, dr);
// (AB)' = (AB') + (A'B)
case Type::Mul:
return new Arithmetic(
Type::Add,
new Arithmetic(Type::Mul, l, dr),
new Arithmetic(Type::Mul, dl, r));
}
}
double eval(double val) override
{
switch (type)
{
case Type::Add:
return l->eval(val) + r->eval(val);
case Type::Sub:
return l->eval(val) - r->eval(val);
case Type::Mul:
return l->eval(val) * r->eval(val);
}
}
private:
enum class Type
{
Add,
Sub,
Mul,
};
Arithmetic(Type _type, Function *_l, Function *_r) : type(_type), l(_l), r(_r) {}
Type type;
Function *l, *r;
};
Function *Polynomial::differential()
{
// (A^b)' = b * (A^(b-1)) * A'
return Arithmetic::create(
exp,
'*',
Arithmetic::create(
new Polynomial(
base,
Constant::create(exp->eval(0) - 1) // problem statement guaranteed that no variable in exp
),
'*',
base->differential()));
}