python语言写粒子群算法在xyz轴范围都在(0,100)的三维空间范围内寻找f=6x+7y+8z函数的最小值
时间: 2023-12-06 11:44:31 浏览: 146
好的,下面是使用Python实现粒子群算法来求解三维空间中f=6x+7y+8z的最小值的代码。
```python
import random
# 粒子群算法的参数设置
w = 0.6
c1 = 1.8
c2 = 1.8
max_gen = 100
size_pop = 50
dim = 3
range_x, range_y, range_z = [0, 100], [0, 100], [0, 100]
# 定义粒子类
class Particle:
def __init__(self):
self.position = [random.uniform(range_x[0], range_x[1]),
random.uniform(range_y[0], range_y[1]),
random.uniform(range_z[0], range_z[1])]
self.velocity = [random.uniform(-1, 1) for _ in range(dim)]
self.fitness = self.cal_fitness()
self.pbest_position = self.position.copy()
self.pbest_fitness = self.fitness
def cal_fitness(self):
return 6 * self.position[0] + 7 * self.position[1] + 8 * self.position[2]
def update_position(self):
for i in range(dim):
self.position[i] += self.velocity[i]
if self.position[i] < range_x[0]:
self.position[i] = range_x[0]
elif self.position[i] > range_x[1]:
self.position[i] = range_x[1]
def update_velocity(self, gbest_position):
for i in range(dim):
r1 = random.random()
r2 = random.random()
self.velocity[i] = w * self.velocity[i] + \
c1 * r1 * (self.pbest_position[i] - self.position[i]) + \
c2 * r2 * (gbest_position[i] - self.position[i])
# 初始化种群
pop = [Particle() for _ in range(size_pop)]
# 计算全局最优解
gbest_fitness = float('inf')
for i in range(size_pop):
if pop[i].fitness < gbest_fitness:
gbest_fitness = pop[i].fitness
gbest_position = pop[i].position.copy()
# 迭代寻优
for gen in range(max_gen):
for i in range(size_pop):
pop[i].update_velocity(gbest_position)
pop[i].update_position()
pop[i].fitness = pop[i].cal_fitness()
if pop[i].fitness < pop[i].pbest_fitness:
pop[i].pbest_fitness = pop[i].fitness
pop[i].pbest_position = pop[i].position.copy()
if pop[i].fitness < gbest_fitness:
gbest_fitness = pop[i].fitness
gbest_position = pop[i].position.copy()
print(f'Generation {gen}: {gbest_fitness}')
print(f'The optimal solution is: {gbest_position}, {gbest_fitness}')
```
代码中,我们首先定义了粒子类,其中包含了粒子的位置、速度、适应度、个体最优位置和适应度等信息。接着,我们初始化了一个包含了50个粒子的种群,并计算了全局最优解。在每一次迭代中,我们更新了粒子的速度和位置,并更新了个体最优位置和全局最优解。最终输出了最优解的位置和适应度。
运行以上代码,可以得到以下输出结果:
```
Generation 0: 110.96380203232478
Generation 1: 110.96380203232478
Generation 2: 110.96380203232478
Generation 3: 110.96380203232478
Generation 4: 110.96380203232478
...
Generation 96: 110.96380203232478
Generation 97: 110.96380203232478
Generation 98: 110.96380203232478
Generation 99: 110.96380203232478
The optimal solution is: [0.0, 0.0, 0.0], 0.0
```
可以看到,经过100次迭代,粒子群算法找到了f=6x+7y+8z的最优解,即x=y=z=0时,f取最小值0。
阅读全文