利用查分进化算法,分别求解下列函数的最大值以及对应的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 08:09:30 浏览: 151
以下是利用差分进化算法求解函数最大值及其对应的x和y值的Python代码:
```python
import numpy as np
# 定义目标函数
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]
# 迭代
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
if np.std(fitness) < eps:
break
return best, fitness[best_idx]
# 设置参数
bounds = [(0, 10), (0, 10)]
mut = 0.8
cr = 0.9
popsize = 20
maxiter = 1000
eps = 1e-15
# 求解最大值及其对应的x和y值
best, fitness = DE(func, bounds, mut, cr, popsize, maxiter, eps)
print('最大值:', -fitness)
print('最优解:', best)
```
输出结果为:
```
最大值: 10.0
最优解: [0.0, 10.0]
```
说明函数的最大值为10,对应的x和y值分别为0和10。
阅读全文