The Beauty and the Mystery of Numbers

I found this as well:

Wiki Mandelbrot Applet Source Code:
_http://wiki.showmedo.com/index.php?title=JavaMontgomeryAppletSeries

For Eclipse: (_http://www.eclipse.org: Development IDE)
Eclipse Tutorial: _http://showmedo.com/videos/video?fromSeriesID=24&name=javaMontgomeryApplet6

For Netbeans: (_http://www.netbeans.org: Development IDE)
_http://web.njit.edu/~gblank/cs602/NetBeans%20Applet%20Text%20File%20Reader.ppt (How to setup applets in NB)

I spent a couple hours cobbling java sources from the Internet and making it all work.
So, For those of you who want a complete Mandelbrot java program, here it is!

Note: These programs can be run as an Applet or as an Application
1) The code was cobbled together from sources on the Internet, so
I do not claim to be the original creator of the code, and AFAIK, it
is given to the public domain.
2) Use at your own risk!
Program is "AS IS", so standard disclaimers apply!

Mandelbrot3 is the best one I have found and it is fast & colorful!
1) You and use the mouse to drag & release the area of interest

Code:
package mandelbrot3;

/*
 * @(#)fractal.java - Fractal Program Mandelbrot Set
 * www.eckhard-roessel.de
 * Copyright (c) Eckhard Roessel. All Rights Reserved.
 * 06/30/2000 - 03/29/2000
 */

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/**
 * @version 1.1
 * @author Eckhard Roessel
 * @modified 03/29/2001
 */
public class Mandelbrot3 extends Applet implements MouseListener, MouseMotionListener
{
    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getPreferredSize() {
        // overridden so app knows how big we want the applet to be
        return new Dimension(1024,1024);
    }

    private static boolean isApp=false;
    
    @SuppressWarnings("deprecation")
	public static void main(String[] args) {
    	isApp = true;
        Frame frame = new Frame("Mandelbrot3");
        frame.addWindowListener(
            new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent we) {
                    // this is called when user tries to close the window
                    // and is a good spot to double check we want to close the window
                    ((Frame)we.getSource()).dispose(); // this does the actual closing
                }
                @Override
                public void windowClosed(WindowEvent we) {
                    // this is called when the window is actually closed (e.g. after calling dispose())
                    System.exit(0); // force VM to terminate and app to finish
                }
            }
        );
        Applet applet = new Mandelbrot3();
        frame.add( applet );
        frame.pack();
        applet.init(); // have to call this ourselves now
        frame.show();

        // now call start on the applet
        applet.start(); // again have to do this ourselves
    }

	private final int MAX = 256;      // max iterations
	private final double SX = -2.025; // start value real
	private final double SY = -1.125; // start value imaginary
	private final double EX = 0.6;    // end value real
	private final double EY = 1.125;  // end value imaginary
	private static int x1, y1, xs, ys, xe, ye;
	private static double xstart, ystart, xende, yende, xzoom, yzoom;
	private static boolean action, rechteck, fertig;
	private static float xy;
	private Image bild;
	private Graphics g1;
	private Cursor c1, c2;

    @Override
	public void init() // all instances will be prepared
	{
		fertig = false;
		addMouseListener(this);
		addMouseMotionListener(this);
		c1 = new Cursor(Cursor.WAIT_CURSOR);
		c2 = new Cursor(Cursor.CROSSHAIR_CURSOR);
		x1 = getSize().width;
		y1 = getSize().height;
		xy = (float)x1 / (float)y1;
		bild = createImage(x1, y1);
		g1 = bild.getGraphics();
		fertig = true;
	}

    @Override
	public void destroy() // delete all instances
	{
		if (fertig)
		{
			removeMouseListener(this);
			removeMouseMotionListener(this);
			bild = null;
			g1 = null;
			c1 = null;
			c2 = null;
			System.gc(); // garbage collection
		}
	}

    @Override
	public void start()
	{
		action = false;
		rechteck = false;
		startwerte();
		xzoom = (xende - xstart) / (double)x1;
		yzoom = (yende - ystart) / (double)y1;
		mandelbrot();
	}
    
    @Override
	public void stop()
	{
	}

    @Override
	public void paint(Graphics g)
	{
		update(g);
	}

    @Override
	public void update(Graphics g)
	{
		g.drawImage(bild, 0, 0, this);
		if (rechteck)
		{
			g.setColor(Color.white);
			if (xs < xe)
			{
				if (ys < ye) g.drawRect(xs, ys, (xe - xs), (ye - ys));
				else g.drawRect(xs, ye, (xe - xs), (ys - ye));
			}
			else
			{
				if (ys < ye) g.drawRect(xe, ys, (xs - xe), (ye - ys));
				else g.drawRect(xe, ye, (xs - xe), (ys - ye));
			}
		}
	}

	private void mandelbrot() // calculate all points
	{
		int x, y;
		float h, b, alt = 0.0f;

		action = false;
		setCursor(c1);
        
                if ( ! isApp ) {
        	        showStatus("Mandelbrot-Set will be produced - please wait...");
                }
		for (x = 0; x < x1; x+=2)
			for (y = 0; y < y1; y++)
			{
				h = punktfarbe(xstart + xzoom * (double)x, ystart + yzoom * (double)y); // color value
				if (h != alt)
				{
					b = 1.0f - h * h; // brightness
					g1.setColor(Color.getHSBColor(h, 0.8f, b));
					alt = h;
				}
				g1.drawLine(x, y, x + 1, y);
			}
		if ( ! isApp ) {
			showStatus("Mandelbrot-Set ready - please select zoom area with pressed mouse.");
		}
		setCursor(c2);
		action = true;
	}

	private float punktfarbe(double xwert, double ywert) // color value from 0.0 to 1.0 by iterations
	{
		double r = 0.0, i = 0.0, m = 0.0;
		int j = 0;

		while ((j < MAX) && (m < 4.0))
		{
			j++;
			m = r * r - i * i;
			i = 2.0 * r * i + ywert;
			r = m + xwert;
		}
		return (float)j / (float)MAX;
	}

	private void startwerte() // reset start values
	{
		xstart = SX;
		ystart = SY;
		xende = EX;
		yende = EY;
		if ((float)((xende - xstart) / (yende - ystart)) != xy )
			xstart = xende - (yende - ystart) * (double)xy;
	}

	public void mousePressed(MouseEvent e)
	{
		e.consume();
		if (action)
		{
			xs = e.getX();
			ys = e.getY();
		}
	}

	public void mouseReleased(MouseEvent e)
	{
		int z, w;

		e.consume();
		if (action)
		{
			xe = e.getX();
			ye = e.getY();
			if (xs > xe)
			{
				z = xs;
				xs = xe;
				xe = z;
			}
			if (ys > ye)
			{
				z = ys;
				ys = ye;
				ye = z;
			}
			w = (xe - xs);
			z = (ye - ys);
			if ((w < 2) && (z < 2)) startwerte();
			else
			{
				if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
				else xe = (int)((float)xs + (float)z * xy);
				xende = xstart + xzoom * (double)xe;
				yende = ystart + yzoom * (double)ye;
				xstart += xzoom * (double)xs;
				ystart += yzoom * (double)ys;
			}
			xzoom = (xende - xstart) / (double)x1;
			yzoom = (yende - ystart) / (double)y1;
			mandelbrot();
			rechteck = false;
			repaint();
		}
	}

	public void mouseEntered(MouseEvent e)
	{
	}

	public void mouseExited(MouseEvent e)
	{
	}

	public void mouseClicked(MouseEvent e)
	{
	}

	public void mouseDragged(MouseEvent e)
	{
		e.consume();
		if (action)
		{
			xe = e.getX();
			ye = e.getY();
			rechteck = true;
			repaint();
		}
	}

	public void mouseMoved(MouseEvent e)
	{
	}

    @Override
    public String getAppletInfo()
	{
		return "fractal.class - Mandelbrot Set a Java Applet by Eckhard Roessel 2000-2001";
	}
}

Mandelbrot1 was the first one I found, it is so-so.

Note: Rested up to MAX_INTERATIONS=1024, Screen resolutions: 1024x1024

1) You and use the mouse to point (center) the area of interest
2) You can use the mouse's thumb-wheel to zoom in/out and watch
the changes on the fly.

Code:
package mandelbrot1;

/* Mandelbrot1
 * http://wiki.showmedo.com/index.php?title=JavaMontgomeryAppletSeries
 */
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.applet.Applet;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Mandelbrot1 extends Applet implements Runnable {
    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getPreferredSize() {
        // overridden so app knows how big we want the applet to be
        return new Dimension(1024,1024);
    }

    public static void main(String[] args) {
        Frame frame = new Frame("Mandelbrot1");
        frame.addWindowListener(
            new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent we) {
                    // this is called when user tries to close the window
                    // and is a good spot to double check we want to close the window
                    ((Frame)we.getSource()).dispose(); // this does the actual closing
                }
                @Override
                public void windowClosed(WindowEvent we) {
                    // this is called when the window is actually closed (e.g. after calling dispose())
                    System.exit(0); // force VM to terminate and app to finish
                }
            }
        );
        Applet applet = new Mandelbrot1();
        frame.add( applet );
        frame.pack();
        applet.init(); // have to call this ourselves now
        frame.show();
        // now call start on the applet
        applet.start(); // again have to do this ourselves
    }

	private Point position = null;
	private Point hello = new Point(0,0);

	private final Object bufferLock = new Object();
	private BufferedImage buffer = null;
	private int[] pixels = null;

	private Rectangle2D.Float initialBounds = new Rectangle2D.Float( -2.1f, -1.5f, 3.0f, 3.0f );
	private Rectangle2D.Float bounds = new Rectangle2D.Float( initialBounds.x, initialBounds.y, initialBounds.width, initialBounds.height );

	private Thread thread = null;

	public final static int MAX_ITERATIONS = 32;

    @Override
    public void start() {
		thread = new Thread( this );
		thread.start();
	}

    @Override
	public void init() {
		synchronized( bufferLock ) {
			buffer = new BufferedImage( getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB );
			pixels = new int[ buffer.getWidth()*buffer.getHeight() ];

			clearPixels();
		}

		addMouseListener(
			new MouseAdapter() {
                @Override
				public void mouseClicked(MouseEvent me) {
					handleClick( me.getX(), me.getY() );
				}
			}
		);

		addMouseWheelListener(
			new MouseWheelListener() {
				public void mouseWheelMoved(MouseWheelEvent mwe) {
					if ( mwe.getWheelRotation() < 0 )
						zoomin();
					else
						zoomout();
				}
			}
		);
	}

	public void run() {
		while( thread == Thread.currentThread() ) {
			tick();
			render();
			try {
				Thread.sleep(40);
			}
			catch( InterruptedException ie ) {}
		}
	}

    @Override
	public void stop() {
		thread = null;
	}

	protected void handleClick( int x, int y ) {
		int screenWidth  = getWidth();
		int screenHeight = getHeight();

		float mx = (bounds.x + bounds.width*(x/(float)screenWidth));
		float my = (bounds.y + bounds.height*(y/(float)screenHeight));

		float cx = bounds.x + bounds.width/2;
		float cy = bounds.y + bounds.height/2;

		float dx = mx-cx;
		float dy = my-cy;

		bounds.x += dx;
		bounds.y += dy;
	}

	protected void zoom( float factor ) {
		float newWidth  = bounds.width*factor;
		float newHeight = bounds.height*factor;

		float dw = bounds.width  - newWidth;
		float dh = bounds.height - newHeight;

		float newX = bounds.x + 0.5f*dw;
		float newY = bounds.y + 0.5f*dh;

		bounds.setRect( newX, newY, newWidth, newHeight );
	}

	protected void zoomin() {
		zoom(0.9f);
	}

	protected void zoomout() {
		zoom(1.1f);
	}

	protected void tick() {
		if ( position != null ) {
			if ( hello.x < position.x ) hello.x++;
			else hello.x--;
			if ( hello.y < position.y ) hello.y++;
			else hello.y--;
		}
	}

	protected int calcIterations( float x, float y ) {
		int iterations = 0;

		float xn = x, yn = y;

		while ( iterations < MAX_ITERATIONS ) {
			float xn1 = xn*xn - yn*yn;
			float yn1 = 2*xn*yn;

			xn = xn1 + x;
			yn = yn1 + y;

			float magsq = xn*xn + yn*yn;

			if ( magsq > 4 )
				break;

			iterations++;
		}

		return iterations;
	}

	private int rgb( int r, int g, int b ) {
		return (r << 64) | (r << 32) | (r << 16) | (g << 8) | b;
	}

	private void setPixel( int x, int y, int rgb ) {
		if ( x >= 0 && y >= 0 && x < buffer.getWidth() && y < buffer.getHeight() ) {
			pixels[ y*buffer.getWidth() + x ] = rgb;
		}
	}

	private void clearPixels() {
		for ( int i = 0; i < pixels.length; i++ ) pixels[ i ] = rgb( 0, 0, 0 );
	}

	private void copyPixels() {
		buffer.setRGB( 0, 0, buffer.getWidth(), buffer.getHeight(), pixels, 0, buffer.getWidth() );
	}

	protected void copyPixelsAndPaint() {
		synchronized( bufferLock ) {
			copyPixels();
		}
		repaint();
		try {
			Thread.sleep(40);
		}
		catch( InterruptedException ie ) {}
	}

	protected int calcPixelColor( int iterations ) {
		int gray = (255*iterations)/MAX_ITERATIONS;

		int r = 80 + 5*(gray*gray)/255;
		int g = 5*(gray*gray)/255;
		int b = gray;

		r = Math.min( r, 255 );
		g = Math.min( g, 255 );
		b = Math.min( b, 255 );

		return rgb( r, g, b );
	}

	protected void renderMandelbrot( float x, float y, float width, float height ) {
		int screenWidth = buffer.getWidth();
		int screenHeight = buffer.getHeight();

		List pixelList = new LinkedList();
		for ( int i = 0; i < screenWidth; i++ ) {
			for ( int j = 0; j < screenHeight; j++ ) {
				pixelList.add( new Point( i, j ) );
			}
		}

		Collections.shuffle( pixelList );

		long start = System.currentTimeMillis();

		while( !pixelList.isEmpty() ) {
			Point pt = (Point)pixelList.remove(0);
			int i = pt.x;
			int j = pt.y;

			float xi = (x + width*(i/(float)screenWidth));
			float yi = (y + height*(j/(float)screenHeight));
			int iterations = calcIterations( xi, yi );
			int pixel = calcPixelColor( iterations );
			setPixel( i, j, pixel );

			if ( (System.currentTimeMillis()-start) > 10 ) {
				copyPixelsAndPaint();
				start = System.currentTimeMillis();
			}
		}

	}

	protected void render() {
		renderMandelbrot( bounds.x, bounds.y, bounds.width, bounds.height );
		synchronized( bufferLock ) {
			copyPixels();
		}
		repaint();
	}

    @Override
	public void update(Graphics g) {
		paint( g );
	}

    @Override
	public void paint( Graphics g ) {
		synchronized( bufferLock ) {
			if ( buffer != null )
				g.drawImage( buffer, 0, 0, null );
		}
	}

}
 
From the java program above @ full color (to hardware):

(1) Mandlebrot1 Complete (1000x1000), 32-Iteration, 90-deg-CW:
MB1.jpg


(2) Mandlebrot1 "Sword Tip" (1000x1000), 64-Iteration, 90-deg-CW, zoomed:
MB2.jpg


(3) Mandlebrot1 "Sword Tip" (1000x1000), 64-Iteration, 90-deg-CW, deep-zoomed (stopped at pixelation):
MB3.jpg


(4) Mandlebrot1, top, slightly-to-left, (800x800), 256-Iteration, zoomed:
MB4.jpg


(5) Mandlebrot1, top, (1000x1000), 512-Iteration, zoomed (notice replication (1)):
MB5.jpg


(6) Mandlebrot3-Fibonacci, top, (1000x1000), 512-Iteration, zoomed
MB6.jpg
 
Can't do anything more but keep staring at all this beautiful pics :) Thanks!
I've hardly managed to run some Basic code here, but Java's is really out of reach :P

Looking forward for some zooming Basic code FWIW, unveiling the mysteries of the Mandelbrot set's neck.
 
What do you mean "Java is really out of reach"?

You can simply download the IDEs as I mentioned, then
update, then add the code to the IDE, and run it. But
you could also learn how to use the IDE and develop
code if you are adventurous :)

Heck, once the IDE is installed you could simply forego
the IDE itself and simply run two commands in a command
window and run it as mentioned in the first link (Wiki)
I provided.

Once you get through the learning process, it's easy really.

It is really cool to be able to navigate through the MB application
and be able to see all sorts of things and you will find self-replicated
images matching the very first one you encountered. Very strange
and mysterious, this "simple" algorthym is!

I am trying to look for correlations to Pi. Phi, or geometric
mysterys to get a handle on what is going on but I am not
going to spend a lifetime setting stuck in the 33 1/3 loop! :)

Dan
 
mkrnhr said:
Hi,
for those who have Matlab, here is a short version of the algorithm for the Mandelbrot figure :
N_pix=1000;
x_min=-2.5;x_max=2;y_min=-2;y_max=2;
x=x_min:(x_max-x_min)/(N_pix-1):x_max;
y=y_min:(y_max-y_min)/(N_pix-1):y_max;
image=zeros(N_pix,N_pix);
for i=1:N_pix
for j=1:N_pix
z=0;
p=0;
c=x(i)+sqrt(-1)*y(j);
while and(abs(z)<2,p<512)
z=z.^2+c;
p=p+1;
end;
image(i,j)=p;
end;
end;
imshow(uint8(image));

And actually setting the second line into
x_min=0.335;x_max=0.46;y_min=0.3;y_max=0.425;
gives this :
 
Really cool site: _http://en.wikipedia.org/wiki/Mandelbrot_set

For those of you who do not want to compile programs
but want to directly examine/zoom mandelbrot sets, just
go here:

_http://javaboutique.internet.com/Mandelbrot/
See complete cleaned up code, in previous thread as "Mandelbrot3"
 
dant said:
Really cool site: _http://en.wikipedia.org/wiki/Mandelbrot_set

For those of you who do not want to compile programs
but want to directly examine/zoom mandelbrot sets, just
go here:

_http://javaboutique.internet.com/Mandelbrot/
See complete cleaned up code, in previous thread as "Mandelbrot3"

Thanks Dant for the zoom tool!

Anyway... I've really few time to dedicate to Java, very interesting though, so, I've installed JDK and Netbeans and now I have a java compiler! But, if the page into the compiler shows this:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mandelbrotzoom;

/**
 *
 * @author Dantem
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

Where to put the _http://javaboutique.internet.com/Mandelbrot/ code :huh:

If I just paste the code on a black page, the compiler tells me that the fractal class is public and should be declared in a file named 'fractal.java'.

Well, nevermind it if it's too long to explain :P
 
Here is how to run the Mandelbrot3 program in Netbeans IDE:
Instructions said:
1) Select: `New Project' icon or menu. A dialog menu pops up.
a) Select `java' in your Category pane
b) Select `java Application' in Project pane
c) Click `Next' button
d) Type in Project name field: Mandelbrot3
e) Click: `Finish' button: Dialog closes, and new project is created in Projects Tab, left pane.

2) If left-pane. 'Projects' tree is not already expanded, expand it. Look for `Main.java' file.
a) Delete `Main.java' file
+ Right-click, and select `Delete'

b) Create a new Java Class and name it Mandelbrot3:
+ Move mouse cursor over `mandelbrot3', right-click, and select `New>Java Class', dialog pops up
+ Type in `Class Name:' field: Mandelbrot3, then click `Finish' button
Editor tab shows default code template in Mandelbrot3.java file in right pane.

c) Delete template code, and copy/paste Mandelbort3 code from forum into Netbeans IDE editor pane
+ Type: Control-A to select all items in Editor-pane, then press 'delete' key.
+ Use mouse to Copy and Paste code from SOTT forum webpage into Netbeans IDE editor pane.

d) Save the file
+ Type: Control-s OR use menu on top-left: File>Save

e) Run the program
+ Click green-arrow icon OR hit F6 function key

This runs the program and a dialog pops up with mandelbrot3 and if the image appears
incomplete, simply click left-button mouse in the mandelbrot3 pane and it will refresh.

Then to zoom in, press in area of interest, holding down left-mouse-button, drag out a
square-area of interest, then release button.

If there are any questions, let me know.

Cheers!
Dan
 
Great!! It works fine, thanks Dant.

This Mandelbrot3 has the full color range! Zooming in... :wizard:
 
Make sure that you get the LATEST updates! I updated
several times to make it more "perfect". I added code to
ensure that running as an applet or application works right
in Mandelbrot3.

BTW: Both Mandelbrot codes work with NetBeans and Eclipse
IDEs. Both IDEs are different but it is not too difficult
to overcome their nuances.

Mandelbrot3 is awesome! You can really zoom much deeper
to a point it becomes pixelated. I do notice that there is a
different picture when compared against Mandelbrot1, especially
that of the "envelopes" as I posted the pictures, above. In
Mandelbrot1, it does make a difference on the MAX_ITERATIONS
value.

I wonder if Ark is interested in this, to switch to using the IDE as
he hasn't responded for awhile. I would also like some pointers
in the changing of the values (in Mandelbrot3):

private final int MAX = 256; // max iterations
private final double SX = -2.025; // start value real
private final double SY = -1.125; // start value imaginary
private final double EX = 0.6; // end value real
private final double EY = 1.125; // end value imaginary

as I am not a mathematician as he is! Is there anything more
we can experiment with?

Kind regards!
Dan
 
Back
Top Bottom