遗传算法的实现,流程如下:
1.初始化种群:随机生成一定数量的染色体,每个染色体由一定数量的基因组成,每个基因的值为0或1。
2.评估种群:对于每个染色体,计算其适应度,即目标函数的值。
3.选择:根据染色体的适应度,选择一定数量的染色体作为下一代的父代。
4.交叉:对于每一对父代,以一定的概率进行交叉操作,生成一个新的子代。
5.变异:对于每个子代,以一定的概率进行变异操作,改变其中的一个或多个基因的值。
6.生成下一代种群:将父代和子代合并,得到下一代种群。
重复2-6步,直到达到停止条件(例如达到最大迭代次数或找到满足要求的解)。
解:在本题中,目标函数为f(x) = Max{1-x^2},-1<=x<=1,其中x为染色体所代表的实数值。每个基因的值为0或1,表示实数值在二进制下的某一位。染色体的适应度为目标函数的值即f(x)。在每一代中,选择操作使用了轮盘赌选择,交叉操作使用了单点交叉,变异操作使用了单点变异。
void initialize_population(vector<Chromosome>& population) {
for (int i = 0; i < POPULATION_SIZE; i++) {
Chromosome chromosome;
for (int j = 0; j < CHROMOSOME_LENGTH; j++) {
chromosome.genes.push_back(dis2(gen) < 0.5 ? 0 : 1);
}
population.push_back(chromosome);
}
}
double decode(vector<int> genes) {
double x = 0.0;
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
x += genes[i] * pow(2, CHROMOSOME_LENGTH - i - 1);
}
return -1.0 + 2.0 * x / (pow(2, CHROMOSOME_LENGTH) - 1);
}
double fitness(vector<int> genes) {
double x = decode(genes);
return 1.0 - x * x;
}
void evaluate(vector<Chromosome>& population) {
for (int i = 0; i < POPULATION_SIZE; i++) {
population[i].fitness = fitness(population[i].genes);
}
}
void sort_population(vector<Chromosome>& population) {
sort(population.begin(), population.end(), compare);
}
bool compare(Chromosome a, Chromosome b) {
return a.fitness > b.fitness;
}
vector<int> crossover(vector<int> parent1, vector<int> parent2) {
vector<int> child;
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
child.push_back(dis2(gen) < CROSSOVER_RATE ? parent1[i] : parent2[i]);
}
return child;
}
void mutate(vector<int>& genes) {
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
if (dis2(gen) < MUTATION_RATE) {
genes[i] = 1 - genes[i];
}
}
}
void next_generation(vector<Chromosome>& population) {
vector<Chromosome> new_population;
for (int i = 0; i < POPULATION_SIZE; i++) {
vector<int> parent1_genes = population[i].genes;
vector<int> parent2_genes = population[dis(gen)].genes;
vector<int> child_genes = crossover(parent1_genes, parent2_genes);
mutate(child_genes);
Chromosome child;
child.genes = child_genes;
new_population.push_back(child);
}
evaluate(new_population);
sort_population(new_population);
population = new_population;
}
for (int i = 0; i < MAX_GENERATIONS; i++) {
if (population[0].fitness >= 1.0 - PRECISION) {
break;
}
next_generation(population);
}
最优解:x = 0.000977517,f(x) = 0.999999
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
const int POPULATION_SIZE = 100;
const int CHROMOSOME_LENGTH = 10;
const double MUTATION_RATE = 0.1;
const double CROSSOVER_RATE = 0.9;
const int MAX_GENERATIONS = 1000;
const double PRECISION = 0.001;
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(-1.0, 1.0);
uniform_real_distribution<> dis2(0.0, 1.0);
struct Chromosome {
vector<int> genes;
double fitness;
};
double decode(vector<int> genes) {
double x = 0.0;
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
x += genes[i] * pow(2, CHROMOSOME_LENGTH - i - 1);
}
return -1.0 + 2.0 * x / (pow(2, CHROMOSOME_LENGTH) - 1);
}
double fitness(vector<int> genes) {
double x = decode(genes);
return 1.0 - x * x;
}
void evaluate(vector<Chromosome>& population) {
for (int i = 0; i < POPULATION_SIZE; i++) {
population[i].fitness = fitness(population[i].genes);
}
}
bool compare(Chromosome a, Chromosome b) {
return a.fitness > b.fitness;
}
void sort_population(vector<Chromosome>& population) {
sort(population.begin(), population.end(), compare);
}
void initialize_population(vector<Chromosome>& population) {
for (int i = 0; i < POPULATION_SIZE; i++) {
Chromosome chromosome;
for (int j = 0; j < CHROMOSOME_LENGTH; j++) {
chromosome.genes.push_back(dis2(gen) < 0.5 ? 0 : 1);
}
population.push_back(chromosome);
}
}
vector<int> crossover(vector<int> parent1, vector<int> parent2) {
vector<int> child;
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
child.push_back(dis2(gen) < CROSSOVER_RATE ? parent1[i] : parent2[i]);
}
return child;
}
void mutate(vector<int>& genes) {
for (int i = 0; i < CHROMOSOME_LENGTH; i++) {
if (dis2(gen) < MUTATION_RATE) {
genes[i] = 1 - genes[i];
}
}
}
void next_generation(vector<Chromosome>& population) {
vector<Chromosome> new_population;
for (int i = 0; i < POPULATION_SIZE; i++) {
vector<int> parent1_genes = population[i].genes;
vector<int> parent2_genes = population[dis(gen)].genes;
vector<int> child_genes = crossover(parent1_genes, parent2_genes);
mutate(child_genes);
Chromosome child;
child.genes = child_genes;
new_population.push_back(child);
}
evaluate(new_population);
sort_population(new_population);
population = new_population;
}
int main() {
vector<Chromosome> population;
initialize_population(population);
evaluate(population);
sort_population(population);
for (int i = 0; i < MAX_GENERATIONS; i++) {
if (population[0].fitness >= 1.0 - PRECISION) {
break;
}
next_generation(population);
}
cout << "最优解: x = " << decode(population[0].genes) << ", f(x) = " << population[0].fitness << endl;
return 0;
}
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只
说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时
我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。
我需要从json记录中获取一些值并像下面这样提取curr_json_doc['title']['genre'].map{|s|s['name']}.join(',')但对于某些记录,curr_json_doc['title']['genre']可以为空。所以我想对map和join()使用try函数。我试过如下curr_json_doc['title']['genre'].try(:map,{|s|s['name']}).try(:join,(','))但是没用。 最佳答案 你没有正确传递block。block被传递给参数括号外的方法
在这段Ruby代码中:ModuleMClassC当我尝试运行时出现“'M:Module'的未定义方法'helper'”错误c=M::C.new("world")c.work但直接从另一个类调用M::helper("world")工作正常。类不能调用在定义它们的同一模块中定义的模块函数吗?除了将类移出模块外,还有其他解决方法吗? 最佳答案 为了调用M::helper,你需要将它定义为defself.helper;结束为了进行比较,请查看以下修改后的代码段中的helper和helper2moduleMclassC
也许这听起来很荒谬,但我想知道这对Ruby是否可行?基本上我有一个功能...defadda,bc=a+breturncend我希望能够将“+”或其他运算符(例如“-”)传递给函数,这样它就类似于...defsuma,b,operatorc=aoperatorbreturncend这可能吗? 最佳答案 两种可能性:以方法/算子名作为符号:defsuma,b,operatora.send(operator,b)endsum42,23,:+或者更通用的解决方案:采取一个block:defsuma,byielda,bendsum42,23,