NANA
gene.cpp
1#include "../include/GA/gene.h"
2#include <cmath>
3#include <random>
4
5
6namespace NANA {
7namespace GA {
8
14static int log2(int value) {
15 int result = 0;
16 while (0 != value)
17 {
18 value >>= 1;
19 ++result;
20 }
21 return result;
22
23
24}
25
26CGeneInt::CGeneInt(int minV, int maxV) :
27 m_minV(minV),
28 m_maxV(maxV) {
29
30}
31
32void CGeneInt::initGene() {
33
34}
35int CGeneInt::translate() {
36 int result = 0;
37
39
40 return result;
41}
42
43
44GeneFloat::GeneFloat(double minV, double maxV, double eps) :
45 m_minV(minV),
46 m_maxV(maxV),
47 m_eps(eps) {
48
50 double range = std::round((maxV - minV) / eps);
51 int nRange = static_cast<int>(range);
52 m_lenGene = log2(nRange);
53 double realRange = std::pow(2.0, m_lenGene) - 1.0;
54 m_rate = range / realRange;
55 m_gene.resize(m_lenGene);
56}
57
58
59
60void GeneFloat::initGene() {
61 for (int i = 0; i < m_lenGene; ++i) {
62 if (0 == (rand() % 2)) {
63 m_gene[i] = false;
64 }
65 else {
66 m_gene[i] = true;
67 }
68 }
70
71 int result = 0.0;
72 for (int i = 0; i < m_lenGene; ++i) {
73 if (m_gene[i])
74 result += std::pow(2, i);
75 }
76
77 int maxVal = m_maxV - m_minV;
78 while (result > maxVal) {
79 int id = rand() % m_lenGene;
80 if (m_gene[id])
81 m_gene[id] = false;
82 result-= std::pow(2, id);
83 }
84
85}
86
87double GeneFloat::translate() {
88 double result = 0.0;
89 for (int i = 0; i < m_lenGene; ++i) {
90 if (m_gene[i])
91 result += std::pow(2.0, i) * m_eps;
92 }
93 result *= m_rate;
94 return result;
95}
96
97void GeneFloat::mutate() {
98 int randid = rand() % m_lenGene;
99 m_gene[randid] = !m_gene[randid];
100}
101
102void GeneFloat::cross(const GeneFloat& father, const GeneFloat& mother, GeneFloat& child1) {
103 int randid = rand() % father.m_lenGene;
104 int i;
105 for (i = 0; i < randid; ++i) {
106 child1.m_gene[i] = father.m_gene[i];
107 }
108 for (; i < father.m_lenGene; ++i) {
109 child1.m_gene[i] = mother.m_gene[i];
110 }
111}
112
113
114
115}
116}