当前位置: 首页 > news >正文

python算术表达式遗传算法

import random
import operator
import math# 定义可能的运算符和操作
ops = {'+': '+','-': '-','*': '*','/': '/','sin': 'math.sin','cos': 'math.cos'
}# 随机生成一个表达式(个体)
def generate_expression(depth=0):if depth > 2:  # 限制表达式的最大深度return str(random.uniform(1, 10))op = random.choice(list(ops.keys()))if op in ['sin', 'cos']:return f"{ops[op]}({generate_expression(depth + 1)})"else:return f"({generate_expression(depth + 1)} {ops[op]} {generate_expression(depth + 1)})"# 评估表达式的适应度
def evaluate_expression(expression):try:return eval(expression)except ZeroDivisionError:return float('inf')  # 避免除以零except Exception as e:return float('inf')  # 处理其他可能的错误# 交叉(将两个表达式合并产生新的个体)
def crossover(expr1, expr2):point = random.randint(0, min(len(expr1), len(expr2)) - 1)return expr1[:point] + expr2[point:]# 变异(随机修改表达式的一部分)
def mutate(expression):return generate_expression() if random.random() < 0.1 else expression# 进化
def evolve(population, generations=100):for _ in range(generations):# 计算适应度fitness = [(evaluate_expression(expr), expr) for expr in population]fitness.sort()# 选择适应度最好的部分作为父代parents = [expr for _, expr in fitness[:len(fitness)//2]]# 生成新的种群population = []while len(population) < len(fitness):parent1, parent2 = random.sample(parents, 2)child = crossover(parent1, parent2)child = mutate(child)population.append(child)# 输出当前最佳表达式和适应度best_expr = fitness[0][1]best_fitness = fitness[0][0]print(f"Best Expression: {best_expr} | Fitness: {best_fitness}")# 初始化种群
population = [generate_expression() for _ in range(20)]
evolve(population)
http://www.lryc.cn/news/423906.html

相关文章:

  • net.sf.jsqlparser.statement.select.SelectItem
  • lua匹配MAC地址 正则表达式
  • Chainlit快速实现AI对话应用并将聊天数据的AWS S3 和 Azure Blob云服务中
  • 浅谈性能优化(基于C++)
  • Python 报错:ModuleNotFoundError: No module named ‘Crypto‘
  • UE(User Equipment) 和 UA(User Agent)
  • 视觉SLAM ch3补充——在Linux中配置VScode以及CMakeLists如何添加Eigen库
  • 开关电源:优化电子产品中的能源使用
  • Java语言程序设计——篇十三(2)
  • python结合csv和正则实现条件筛选数据统计分数
  • Ubuntu系统的基础操作和使用|Linux|安装|网络连接|更新与升级系统|系统维护|故障排除|监控|桌面环境|虚拟机|快捷键
  • day 38
  • 352532
  • Day.38 | 1143.最长公共子序列 1035.不相交的线 53.最大子序和 392.判断子序列
  • pytorch 3 计算图
  • 一文吃透:暗水印是什么?企业防泄密可以加暗水印吗?
  • Ajax-02.Axios
  • NodeJS的核心配置文件package.json和package.lock.json详解
  • 开源数据采集和跟踪系统:助力营销决策的关键工具
  • Luminar Neo for Mac/Win:创新AI图像编辑软件的强大功能
  • Mac平台M1PRO芯片MiniCPM-V-2.6网页部署跑通
  • MyBatis:Maven,Git,TortoiseGit,Gradle
  • 获取链表中间位置的两种方法方法
  • 第二十天的学习(2024.8.8)Vue拓展
  • 微信小程序教程011:全局配置:Window
  • Tomcat服务器和Web项目的部署
  • PCIe学习笔记(22)
  • Vue3 依赖注入Provide / Inject
  • Python | Leetcode Python题解之第332题重新安排行程
  • React状态管理:react-redux和redux-saga(适合由vue转到react的同学)