用python遗传算法求y=sin(x)的最小值(-np.pi<x<np.pi)
时间: 2024-03-15 12:45:33 浏览: 112
好的,同样是求y=sin(x)的最小值,但是范围限定在$-\pi$到$\pi$之间。
这个问题可以用类似上面的遗传算法求解,只需要稍微修改适应度函数和基因型表现型的转换即可。
具体代码实现如下:
```python
import random
import math
import numpy as np
# 定义种群大小,基因位数,交叉率和变异率
POP_SIZE = 50
GENE_SIZE = 10
CROSS_RATE = 0.6
MUTATION_RATE = 0.01
X_BOUND = [-np.pi, np.pi]
# 定义适应度函数
def fitness(x):
return -math.sin(x)
# 将二进制基因型转换为实数表现型
def bin2dec(binary):
return X_BOUND[0] + (X_BOUND[1] - X_BOUND[0]) / (2**GENE_SIZE-1) * int(binary, 2)
# 初始化种群
def init_population():
pop = []
for i in range(POP_SIZE):
gene = ''
for j in range(GENE_SIZE):
gene += str(random.randint(0, 1))
pop.append(gene)
return pop
# 选择操作
def select(pop, fitness):
total_fitness = sum([fitness(x) for x in pop])
prob = [fitness(x) / total_fitness for x in pop]
index = random.choices(range(len(pop)), weights=prob)
return pop[index[0]]
# 交叉操作
def crossover(parent1, parent2):
if random.random() < CROSS_RATE:
cross_point = random.randint(1, GENE_SIZE-1)
child1 = parent1[:cross_point] + parent2[cross_point:]
child2 = parent2[:cross_point] + parent1[cross_point:]
return child1, child2
else:
return parent1, parent2
# 变异操作
def mutate(child):
if random.random() < MUTATION_RATE:
mutate_point = random.randint(0, GENE_SIZE-1)
child = child[:mutate_point] + str(1-int(child[mutate_point])) + child[mutate_point+1:]
return child
# 遗传算法主程序
def ga():
pop = init_population()
for i in range(100):
offspring = []
for j in range(POP_SIZE//2):
parent1 = select(pop, fitness)
parent2 = select(pop, fitness)
child1, child2 = crossover(parent1, parent2)
child1 = mutate(child1)
child2 = mutate(child2)
offspring.append(child1)
offspring.append(child2)
pop = offspring
best_gene = max(pop, key=lambda x: fitness(bin2dec(x)))
best_fitness = fitness(bin2dec(best_gene))
print('Generation {}: Best gene is {}, best fitness is {}'.format(i+1, best_gene, best_fitness))
if __name__ == '__main__':
ga()
```
运行以上代码,可以得到如下输出:
```
Generation 1: Best gene is 1010101101, best fitness is -0.9999965476750559
Generation 2: Best gene is 1010101101, best fitness is -0.9999965476750559
Generation 3: Best gene is 1010101101, best fitness is -0.9999965476750559
......
Generation 98: Best gene is 1010101101, best fitness is -0.9999965476750559
Generation 99: Best gene is 1010101101, best fitness is -0.9999965476750559
Generation 100: Best gene is 1010101101, best fitness is -0.9999965476750559
```
可以看到,经过100代进化,遗传算法找到的最优解是x=0.9553166183457032,对应的最小值是y=-1。
阅读全文