From 6fd23da97fa9700f59c61a966b4bf7d25fa46b34 Mon Sep 17 00:00:00 2001 From: Paul Oliver Date: Thu, 29 Feb 2024 03:15:03 +0100 Subject: initial commit --- NNUtils.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 NNUtils.cpp (limited to 'NNUtils.cpp') diff --git a/NNUtils.cpp b/NNUtils.cpp new file mode 100644 index 0000000..611768a --- /dev/null +++ b/NNUtils.cpp @@ -0,0 +1,54 @@ +#include "NNUtils.hpp" + +std::default_random_engine rGenerator; + +void seedRand() +{ + rGenerator.seed(std::chrono::system_clock::now().time_since_epoch().count()); +} + +float realRand(float low, float hi) +{ + std::uniform_real_distribution fDistributor(low, hi); + return fDistributor(rGenerator); +} + +int intRand(int low, int hi) +{ + std::uniform_int_distribution iDistributor(low, hi - 1); + return iDistributor(rGenerator); +} + +float sigmoid(float input, float sensitivity) +{ + return 1.f / (1.f + expf(-input / sensitivity)); +} + +void crossover(const Chromosome &parent, const Chromosome &mother, Chromosome &child1, Chromosome &child2) +{ + if (parent.size() != mother.size()) + { + return; + } + + child1.clear(); + child2.clear(); + + int cop = intRand(0, parent.size()); + + child1.insert(child1.end(), parent.begin(), parent.begin() + cop); + child1.insert(child1.end(), mother.begin() + cop, mother.end()); + child2.insert(child2.end(), mother.begin(), mother.begin() + cop); + child2.insert(child2.end(), parent.begin() + cop, parent.end()); +} + +void mutate(Chromosome &chromosome, float mutationRate) +{ + for (auto &i : chromosome) + { + if (realRand(0.f, 1.f) < mutationRate) + { + i = realRand(-1.f, 1.f); + } + } +} -- cgit v1.2.1