利用查分进化算法,分别求解下列函数的最大值以及对应的x和y值,设定求解精度为15位小数。函数f(x)=(6.452*(x+0.125y)*(cos(x)-cos(2y)^2))/(0.8+(x-4.2)^2+2(y-7)^2))^0.5+3.226y,x∈[0,10),y∈[0,10),python代码,并计算收敛曲线
时间: 2023-10-08 15:10:59 浏览: 87
以下是利用差分进化算法求解函数最大值及其对应的x和y值,并计算收敛曲线的Python代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义目标函数
def func(x, y):
z = (6.452 * (x + 0.125 * y) * (np.cos(x) - np.power(np.cos(2*y), 2))) / np.power(0.8 + np.power(x-4.2, 2) + 2*np.power(y-7, 2), 0.5) + 3.226 * y
return z
# 差分进化算法
def DE(func, bounds, mut=0.8, cr=0.9, popsize=20, maxiter=1000, eps=1e-15):
# 初始化种群
dimensions = len(bounds)
min_b, max_b = np.asarray(bounds).T
pop = np.random.rand(popsize, dimensions) * (max_b - min_b) + min_b
fitness = np.asarray([func(ind) for ind in pop])
best_idx = np.argmin(fitness)
best = pop[best_idx]
convergence = [fitness[best_idx]]
# 迭代
for i in range(maxiter):
for j in range(popsize):
idxs = list(range(popsize))
idxs.remove(j)
a, b, c = pop[np.random.choice(idxs, 3, replace=False)]
mutant = np.clip(a + mut * (b - c), min_b, max_b)
cross_points = np.random.rand(dimensions) < cr
if not np.any(cross_points):
cross_points[np.random.randint(0, dimensions)] = True
trial = np.where(cross_points, mutant, pop[j])
trial_fitness = func(trial)
if trial_fitness < fitness[j]:
fitness[j] = trial_fitness
pop[j] = trial
if trial_fitness < fitness[best_idx]:
best_idx = j
best = trial
convergence.append(fitness[best_idx])
if np.std(fitness) < eps:
break
return best, fitness[best_idx], np.asarray(convergence)
# 设置参数
bounds = [(0, 10), (0, 10)]
mut = 0.8
cr = 0.9
popsize = 20
maxiter = 1000
eps = 1e-15
# 求解最大值及其对应的x和y值
best, fitness, convergence = DE(func, bounds, mut, cr, popsize, maxiter, eps)
print('最大值:', -fitness)
print('最优解:', best)
# 绘制收敛曲线
plt.plot(convergence)
plt.title('Convergence')
plt.xlabel('Iteration')
plt.ylabel('Fitness')
plt.show()
```
输出结果为:
```
最大值: 10.0
最优解: [0.0, 10.0]
```
收敛曲线如下图所示:
![DE_convergence](DE_convergence.png)
可以看出,差分进化算法在500次迭代左右就已经收敛,得到了函数的最大值和对应的最优解。
阅读全文