Most beautiful Mathematics formula:Mandelbrot Set
1 public unsafe class MandelbrotSet 2 { 3 public Bitmap bmp = null; 4 public BitmapData bd = null; 5 public int[] data = null; 6 public Point[] pts = null; 7 8 public int width; //pexils 9 public int height; 10 public double scall = 3; 11 public int initLevel; 12 13 public double startx, starty, endx, endy; 14 15 public MandelbrotSet(int width, int height, double scall, int initLevel) 16 { 17 this.width = width; 18 this.height = height; 19 this.scall = scall; 20 21 this.startx = -1 * (scall / 2)*((double)width/height); 22 this.endx = (scall / 2) * ((double)width / height); 23 24 this.starty = (scall/2); 25 this.endy = -1*(scall/2); 26 27 this.initLevel = initLevel; 28 pts = new Point[width * height]; 29 data = new int[width * height]; 30 31 for (int y = 0; y < height; y++) 32 { 33 for (int x = 0; x < width; x++) 34 { 35 pts[x + y * width] = new Point(x, y); 36 } 37 } 38 39 this.bmp = new Bitmap(width, height); 40 using (var g = Graphics.FromImage(bmp)) 41 { 42 g.Clear(Color.Black); 43 g.DrawString("123", new Font("Lucida Console", 12), new SolidBrush(Color.Red), new PointF(0, 0)); 44 } 45 46 } 47 48 public void Calculate() 49 { 50 bd = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); 51 52 double unitx = (double)1/width; 53 double unity = (double) 1/height; 54 pts.AsParallel().ForAll(pt => 55 { 56 Complex c = new Complex(pt.X * unitx * (endx - startx) + startx, (double)pt.Y *unity * (endy - starty) + starty); 57 Complex z = 0; 58 59 60 61 int count = 0; 62 do 63 { 64 z = z * z + c; 65 count++; 66 } 67 while (z.Magnitude < 4 && count < initLevel); 68 //return count; 69 70 double _value; 71 if (count == 0) 72 _value = 0; 73 else 74 _value = Math.Log(count) / Math.Log(initLevel); 75 76 Color cl = Color.FromArgb(0xFF, (int)(Math.Sin(_value * Math.PI) * 0xFF), (int)(Math.Sin(_value * Math.PI) * 0xFF), 0); 77 UnsafeSetPixel(pt.X, pt.Y, cl.R, cl.G, cl.B); 78 79 }); 80 bmp.UnlockBits(bd); 81 } 82 83 84 public void UnsafeSetPixel(int x, int y, byte r, byte g, byte b) 85 { 86 byte* row = (byte*)bd.Scan0 + (y * bd.Stride); 87 row[x * 4] = b; //Blue 0-255 88 row[x * 4 + 1] = g; //Green 0-255 89 row[x * 4 + 2] = r; //Red 0-255 90 //row[x * 4 + 3] = 100; //Alpha 0-255 91 } 92 }
posted on 2013-04-12 23:10 Henry_Wang 阅读(206) 评论(0) 编辑 收藏 举报