1#include "../include/GA/gene.h"
14static int log2(
int value) {
26CGeneInt::CGeneInt(
int minV,
int maxV) :
32void CGeneInt::initGene() {
35int CGeneInt::translate() {
44GeneFloat::GeneFloat(
double minV,
double maxV,
double eps) :
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);
60void GeneFloat::initGene() {
61 for (
int i = 0; i < m_lenGene; ++i) {
62 if (0 == (rand() % 2)) {
72 for (
int i = 0; i < m_lenGene; ++i) {
74 result += std::pow(2, i);
77 int maxVal = m_maxV - m_minV;
78 while (result > maxVal) {
79 int id = rand() % m_lenGene;
82 result-= std::pow(2,
id);
87double GeneFloat::translate() {
89 for (
int i = 0; i < m_lenGene; ++i) {
91 result += std::pow(2.0, i) * m_eps;
97void GeneFloat::mutate() {
98 int randid = rand() % m_lenGene;
99 m_gene[randid] = !m_gene[randid];
102void GeneFloat::cross(
const GeneFloat& father,
const GeneFloat& mother, GeneFloat& child1) {
103 int randid = rand() % father.m_lenGene;
105 for (i = 0; i < randid; ++i) {
106 child1.m_gene[i] = father.m_gene[i];
108 for (; i < father.m_lenGene; ++i) {
109 child1.m_gene[i] = mother.m_gene[i];