NINのブログ

主に機械学習とか統計モデリングとか金融とか

Sierpinskiの三角形

ProcessingでSierpinskiの三角形を描きます。
フラクタルとしての性質を持つSierpinskiの三角形は、再帰関数を用いて書くのが良いでしょう。

void setup() {
  size(600, 600, P3D);
  colorMode(RGB,256);
  background(#050000);
  smooth();
  fill(#FFFFFF);
  triangle(300,130,100,470,500,470);
}

void circlesR(float x1, float y1, float x2, float y2, float x3, float y3, int n) {
  triangle((x1+x2)/2,(y1+y2)/2,(x2+x3)/2,(y2+y3)/2,(x3+x1)/2,(y3+y1)/2);
  if (n>1) {
  circlesR(x1,y1,(x1+x2)/2,(y1+y2)/2,(x1+x3)/2,(y1+y3)/2,n-1);
  circlesR(x2,y2,(x1+x2)/2,(y1+y2)/2,(x2+x3)/2,(y2+y3)/2,n-1);
  circlesR(x3,y3,(x2+x3)/2,(y2+y3)/2,(x1+x3)/2,(y1+y3)/2,n-1);
  }
}

void draw(){
    fill(#050000);
    circlesR(300,130,100,470,500,470,4);
    save("4.png"); 
}

再帰の深さ1
f:id:RYNIN:20140809011347p:plain
再帰の深さ3
f:id:RYNIN:20140809011354p:plain
再帰の深さ4
f:id:RYNIN:20140809011632p:plain
再帰の深さ6
f:id:RYNIN:20140809011359p:plain