巴恩斯利蕨

来源:互联网 发布:中国古典音乐 知乎 编辑:程序博客网 时间:2024/06/03 13:12

巴恩斯利蕨C++实现

简单介绍一下巴恩斯利蕨算法,学过计算机图形学的都应该听说过巴恩斯利蕨算法,这个变形算法,是通过概率分布的不同经过若干次迭代过程,实现分型,最终得到我们所说的巴恩斯利蕨(一种蕨类植物)这里不妨先贴出最终的效果图。
这里写图片描述

巴恩斯利蕨利用了四个公式如下表

公式序号 a b c d e f P(概率) 1 0 0 0 0.16 0 0 0.01 2 0.85 0.04 -0.04 0.85 0 1.6 0.85 3 0.2 -0.26 0.23 0.22 0 1.6 0.07 3 -0.15 0.28 0.26 0.24 0 0.44 0.07

x’ = a*x+b*y+e
y’ = c*x+d*y+f

下面用C++实现,这里老书都是介绍graphics,但这个TC库很老了,都已经被淘汰了,which has been eliminated now, so let us use something new, OpenGL. OpenGL的入门可以参考博文。

#include <GL/glut.h>#include<stdlib.h>#include<stdio.h>#include<math.h>#include<time.h>void fractalFern(void){    glClear(GL_COLOR_BUFFER_BIT);    glColor3f(0.4f, 0.8f, 0.4f);    glBegin(GL_POINTS);    GLfloat x=0,y=0;    srand((unsigned)time(0));    for (int i = 0; i < 50000;i++){            int n = (int) 100*rand()/(RAND_MAX + 1);            //printf("%d ", n);            GLfloat _x, _y;            if (n < 1){                _x = 0; _y = 0.16*y;            }            else if(n < 8){                _x = 0.2*x - 0.26*y;                _y = 0.23*x + 0.22*y + 1.6;            }            else if (n < 15){                _x = -0.15*x + 0.28*y;                _y = 0.26*x + 0.24*y + 0.44;            }            else{                _x = 0.85*x + 0.04*y;                _y = -0.04*x + 0.85*y + 1.6;            }            x = _x;            y = _y;            glVertex2f(_x/10, _y/10-0.3);            glFlush();    }    glEnd();    glFlush();}int main(int argc, char* argv[]){    glutInit(&argc, argv);    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);    glutInitWindowPosition(100, 100);    glutInitWindowSize(450, 450);    glutCreateWindow("巴恩斯利蕨");    glutDisplayFunc(&fractalFern);    glutMainLoop();    return 0;}

这里提供JavaScript语法的实现连接巴恩斯利蕨

实现都是小事,重要的是要学会算法的思想,我们可以从巴恩斯利蕨算法中学到迭代的思想,而在数据结构中,迭代往往会比递归效率高好多。

1 0