數學的藝術——迭代函式下的圖案(Java繪圖)
阿新 • • 發佈:2020-10-25
迭代,其實就是一個重複反饋的過程,利用舊值推新值,即:xn+1=f(xn)。
當我們要在一個平面上繪圖的時候就需要一個座標(x,y),我們只要把每一個迭代後的(xn+1,yn+1)繪製出來就好了。
下面給出了幾個比較簡單有趣的迭代函式(來源:http://paulbourke.net/fractals/ifs/):
Maple Leaf: xn+1= a xn+ b yn+ e
yn+1= c xn+ d yn+ f
引數:
set 1 set 2 set 3 set 4 a 0.1400 0.4300 0.4500 0.4900 b 0.0100 0.5200 -0.4900 0.0000 c 0.0000 -0.4500 0.4700 0.0000 d 0.5100 0.5000 0.4700 0.5100 e -0.0800 1.4900 -1.6200 0.0200 f -1.3100 -0.7500 -0.7400 1.6200
TREE:xn+1= axn+ byn+ e
yn+1= cxn+ dyn+ f
引數:
set 1 set 2 set 3 set 4 a 0.0100 -0.0100 0.4200 0.4200 b 0.0000 0.0000 -0.4200 0.4200 c 0.0000 0.0000 0.4200 -0.4200 d 0.4500 -0.4500 0.4200 0.4200 e 0.0000 0.0000 0.0000 0.0000 f 0.0000 0.4000 0.4000 0.4000
TREE的程式碼(在MouseListener中實現)
1 import java.awt.Color; 2 import java.awt.Graphics; 3 import java.awt.event.MouseEvent; 4 import java.awt.event.MouseListener; 5 import java.util.Random; 6 7 public class Listener implements MouseListener { 8 Graphics g; 9 double[] a = {0.0100,-0.0100,0.4200,0.4200};10 double[] b = {0.0000,0.0000,-0.4200,0.4200}; 11 double[] c = {0.0000,0.0000,0.4200,-0.4200}; 12 double[] d = {0.4500,-0.4500,0.4200,0.4200}; 13 double[] e1 = {0.0000,0.0000,0.0000,0.0000}; 14 double[] f = {0.0000,0.4000,0.4000,0.4000}; 15 16 @Override 17 public void mouseClicked(MouseEvent e) { 18 // TODO Auto-generated method stub 19 double x = 0 , y = 0; 20 Random t = new Random(); 21 Color cl = new Color(200,70,43); 22 g.setColor(cl); 23 for (int i = 0 ; i < 1500000 ; i++) 24 { 25 int n = t.nextInt(499)%4; 26 double tempx = a[n]*x+b[n]*y+e1[n]; 27 double tempy = c[n]*x+d[n]*y+f[n]; 28 x = tempx; 29 y = tempy; 30 int px = (int)(tempx*500)+e.getX(); 31 int py = -((int)(tempy*500)+e.getY())+3*e.getX(); 32 g.drawLine(px, py, px, py); 33 34 } 35 } 36 37 @Override 38 public void mousePressed(MouseEvent e) { 39 // TODO Auto-generated method stub 40 41 } 42 43 @Override 44 public void mouseReleased(MouseEvent e) { 45 // TODO Auto-generated method stub 46 47 } 48 49 @Override 50 public void mouseEntered(MouseEvent e) { 51 // TODO Auto-generated method stub 52 g.setColor(Color.white); 53 g.fillRect(0, 0, 800, 800); 54 } 55 56 @Override 57 public void mouseExited(MouseEvent e) { 58 // TODO Auto-generated method stub 59 60 } 61 }
效果: