上传者: 48130370
|
上传时间: 2021-03-03 15:38:20
|
文件大小: 1KB
|
文件类型: PY
#运用python实现差分进化算法计算函数最大值
import random
import math
import numpy as np
import random
cr = 0.6
Population = np.random.rand(100,2)
cycle = 500
hig , low = math.pi , 0
def eval(x):
y = 2*math.sin(x[0])+math.cos(x[1])
return y
def main():
for t in range(cycle):#确定迭代次数
for i in range(len(Population)):#遍历种群中每一个个体
loc = np.random.randint(0,100,3)#生成三个随机整数,用于公式中随机选取三个点
new = Population[loc[0]] + 0.3*(Population[loc[1]]-Population[loc[2]])#老师给的公式
if random.random() eval(Population[i]):#优胜劣汰
Population[i] = new
for j in range(len(Population[i])):#设置函数取值范围
if Population[i][j] hig:
Population[i][j] = hig
def result():
main()
y_best = []
for i in range(len(Population)):
y_best.append(eval(Population[i]))
print("函数在x为",Population[y_best.index(max(y_best))],"时取得最大值")
print("此时函数结果为:",max(y_best))
result()