-
Notifications
You must be signed in to change notification settings - Fork 0
/
induction.h
45 lines (37 loc) · 1.24 KB
/
induction.h
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
/* implements forwards and backwards induction on a lattice */
#include <functional>
#include <array>
#include "lattice.h"
const int laticeNomial = 2;//binomial
template<typename T>
void forwardInduction(T rootVal, Lattice<T, laticeNomial>& lattice,
const std::function<std::array<T, laticeNomial>(T)>& gen)
{
lattice(0, 0) = rootVal;
for(size_t i = 0; i < lattice.maxIndex(); i++){
for(size_t j = 0; j <= i; j++){
auto arr = gen(lattice(i, j));
lattice(i+1, j) = arr[0];
lattice(i+1, j + 1) = arr[1];
}
}
}
template<typename T>
T backwardsInduction(Lattice<T, laticeNomial>& lattice,
const std::function<T(std::array<T, laticeNomial>, T)>& backGen,
const std::function<T(T)>& leafGen,
const std::function<T(T,T)>& adjust)
{
for(size_t j = 0; j < lattice.size1(); j++){
lattice(lattice.maxIndex() , j) = leafGen(lattice(lattice.maxIndex() , j));
}
for(long i = lattice.maxIndex() - 1; i >= 0; i--){
for(long j = 0; j <= i; j++){
std::array<T, laticeNomial> arr{lattice(i+1, j), lattice(i+1, j + 1)};
T latticeVal = lattice(i, j);
lattice(i, j) = backGen(arr, lattice(i, j));
lattice(i, j) = adjust(latticeVal, lattice(i, j));
}
}
return lattice(0,0);
}