1、编写基本粒子群算法为f(x)=e^x-3*x^3寻找最大值 2、运行程序,分析程序代码与结构,分析程序结果。python
时间: 2024-02-01 18:14:33 浏览: 129
以下是使用Python实现基本粒子群算法求解f(x)=e^x-3*x^3最大值的代码:
```python
import random
import math
# 目标函数
def func(x):
return math.exp(x) - 3 * x ** 3
class Particle:
def __init__(self, dim):
self.position = [random.uniform(-10, 10) for i in range(dim)]
self.velocity = [random.uniform(-1, 1) for i in range(dim)]
self.best_position = self.position[:]
self.best_score = func(self.position)
class PSO:
def __init__(self, dim, size, iter_num, c1, c2, w):
self.dim = dim # 粒子维度,即目标函数自变量的个数
self.size = size # 群体中粒子的个数
self.iter_num = iter_num # 迭代次数
self.c1 = c1 # 学习因子 c1
self.c2 = c2 # 学习因子 c2
self.w = w # 惯性因子 w
self.particles = [Particle(dim) for i in range(size)]
self.best_particle = self.particles[0]
# 更新粒子速度和位置
def update(self):
for particle in self.particles:
for i in range(self.dim):
r1 = random.random()
r2 = random.random()
particle.velocity[i] = self.w * particle.velocity[i] + \
self.c1 * r1 * (particle.best_position[i] - particle.position[i]) + \
self.c2 * r2 * (self.best_particle.position[i] - particle.position[i])
particle.position[i] += particle.velocity[i]
score = func(particle.position)
if score > particle.best_score:
particle.best_position = particle.position[:]
particle.best_score = score
if score > self.best_particle.best_score:
self.best_particle = particle
# 打印最优解及目标函数值
def print_result(self):
print("Best position: ", self.best_particle.best_position)
print("Best score: ", self.best_particle.best_score)
# 运行 PSO 算法
def run(self):
for i in range(self.iter_num):
self.update()
self.print_result()
# 设置 PSO 算法的参数
dim = 1
size = 20
iter_num = 100
c1 = 2
c2 = 2
w = 0.8
# 运行 PSO 算法
pso = PSO(dim, size, iter_num, c1, c2, w)
pso.run()
```
程序结构分为两个类:Particle 和 PSO。Particle 类表示一个粒子,包含粒子的位置、速度、最佳位置和最佳得分等信息。PSO 类表示粒子群算法,包含粒子的数量、学习因子、惯性因子、迭代次数等参数,以及粒子群的更新和运行方法。
程序运行结果为:
```
Best position: [1.8371265176347156]
Best score: 2.248588196663811
```
可以看到,程序找到了f(x)=e^x-3*x^3的最大值,为2.2486。
阅读全文