手拉手,一起走

力的进化:智能火箭

2022-08-17  本文已影响0人  大龙10

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第9章目录

9.10 力的进化:智能火箭

1、问题

2、思路

class Rocket {
    PVector location; 火箭有3个向量:位置、速度和加速度
    PVector velocity;
    PVector acceleration;
    void applyForce(PVector f) { 将力转化为加速度(牛顿第二定律)
        acceleration.add(f);
    }
    void update() { 简单的物理模型(欧拉积分)
        velocity.add(acceleration); 速度根据加速度变化
        location.add(veloctiry); 位置根据速度变化
        acceleration.mult(0);
    }
}

3、定制遗传算法

  上一节提到了定制遗传算法的3个关键点,下面结合本例回顾这3个关键点。

1)第1点:种群规模和突变率

2)第2点:适应度函数

void fitness() {
    float d = PVector.dist(location, target); 计算距离
    fitness = 1/d; 适应度和距离成反比
}
void fitness() {
    float d = PVector.dist(location, target);
    fitness = pow(1/d,2); 1除以距离的平方
}

3)第3点:基因型和表现型

class DNA {
    PVector[] genes;
PVector v = new PVector(random(-1,1),random(-1,1));
for (int i = 0; i < genes.length; i++) {
    genes[i] = PVector.random2D(); 按随机角度创建向量
}
class DNA {
    PVector[] genes; 基因序列是一组向量
    float maxforce = 0.1; 推进器的推力大小
    DNA() {
        genes = new PVector[lifetime]; 火箭生命期的每一帧分别对应一个向量对象
        for (int i = 0; i < genes.length; i++) {
            genes[i] = PVector.random2D();
            genes[i].mult(random(0, maxforce)); 用随机的方式改变向量长度,但不要超过最大推}
        }
    }
class Rocket {
    DNA dna; 火箭的DNA
    float fitness; 火箭的适应度
    PVector location;
    PVector velocity;
    PVector acceleration;
int geneCounter = 0;
void run() {
    applyForce(dna.genes[geneCounter]); 将基因数组中的力向量作用在火箭上
    geneCounter++; 转到基因数组的下一个力向量
    update(); 更新火箭的物理属性
}
上一篇下一篇

猜你喜欢

热点阅读