Commit d1ed25f5 authored by rworreby's avatar rworreby

Add Exercise 12

parent c7158184
/*
* Programming Techniques for Scientific Simulations I
* HS 2020
* Exercise 12
*/
#include <iostream>
#include "algorithmic_derivation.hpp"
// expression: 5*x*(x+1)+72*x+38 = 5*x^2 + 77*x + 38
// derivative: 10*x+77
int expr(const int _x) {
Variable<int> x;
return ( constant(5) * x * (x + constant(1))
+ constant(72) * x + constant(38)
)(_x);
}
int expr_deriv(const int _x) {
Variable<int> x;
return ( constant(5) * x * (x + constant(1))
+ constant(72) * x + constant(38)
).derivative(_x);
}
int main() {
std::cout << expr(8) << ' ' << expr_deriv(8) << std::endl;
return 0;
}
/*
* Programming Techniques for Scientific Simulations I
* HS 2020
* Exercise 12
*/
#ifndef ALGO_DERIVATION
#define ALGO_DERIVATION
enum OP_enum {Add, Multiply};
//********
template<typename T>
class Constant {
public:
Constant(const T & v) : val_(v) {}
T operator()(const T &) const {
return /*to be implemented*/
}
T derivative(const T &) const {
return /*to be implemented*/
}
private:
T val_;
};
// this function is just here so we don't need to write <int>. The function
// can deduce it (whereas the class can't)
template <typename T>
Constant<T> constant(const T & x) {
return Constant<T>(x);
}
//********
template <typename T>
class Variable {
public:
T operator()(const T & x) const {
return /*to be implemented*/
}
T derivative(const T & x) const {
return /*to be implemented*/
}
};
//********
template<typename L, typename R, OP_enum op>
class Expression {
public:
Expression(const L & l, const R & r) : l_(l), r_(r) { }
template <typename T>
T operator()(const T & x) const {
switch (op) { // we could just as well use if ... else if .... else
case Add:
return /*to be implemented*/
case Multiply:
return /*to be implemented*/
}
}
template <typename T>
T derivative(const T & x) const {
switch (op) {
case Add:
return /*to be implemented*/
case Multiply:
return /*to be implemented*/
}
}
private:
L l_;
R r_;
};
//********
template<typename L, typename R>
Expression<L, R, Multiply> operator*(const L & l, const R & r) {
return Expression<L, R, Multiply>(l, r);
}
template<typename L, typename R>
Expression<L, R, Add> operator+(const L & l, const R & r) {
return Expression<L, R, Add>(l, r);
}
#endif //ALGO_DERIVATION
import copy
import numpy as np
import random
# Store the genes as a numpy.array(dtype=bool).
gene_size = 64
# Genes set to all good.
genes_1 = np.zeros(gene_size, dtype=bool)
# Access individual gene with [ ].
print(genes_1[0])
# Deep copy genes_1.
genes_2 = copy.deepcopy(genes_1)
# Random numbers
# Seed the RNG.
random.seed(0)
# Random floating point number in the range [0.0, 1.0).
print(random.random())
# Random integer in the range [0, gene_size-1].
print(random.randint(0, gene_size - 1))
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment