/*********************************************************

File: BrownianMotion3.java
Author: Jim Carlson (copyright) 1996
web: http://www.math.utah.edu/~carlson
e-mail: carlson@math.utah.edu
Date:June 6, 1996

Legal stuff: All rights reserved, but noncommercial use is free

Simulation of Brownian motion.   The guts of the program is
the loop labelled (XX).

**********************************************************/

import java.applet.*;
import java.awt.*;
import CGraphics;
import java.util.Random;

public class BrownianMotion extends Applet {

	// bounding box in Cartesian coordinates:
	double a = -1; double b = 1; // range of x
	double c = -1; double d = 1; // range of y
	
	CGraphics G;
	Random R = new Random();
	
	int n = 100; 
	double dx = 0.2;
	double dy = 0.2;
	double xStart = 0; double yStart = 0;
	double xFinish; double yFinish; 
    
	
	// size in screen coordinates of the  CGraphics object
	int w, h; 
	
	public void init(){
	
		String x;
	
		x = getParameter("n");
		if ( x != null )
			n = Integer.parseInt(x);
		else
			n = 100;
			
		x = getParameter("dx");
		if ( x != null )
			dx = Double.valueOf(x).doubleValue();
		else
			dx = 0.2;
			
		x = getParameter("dy");
		if ( x != null )
			dy = Double.valueOf(x).doubleValue();
		else
			dy = 0.2;	
	}
		
	 
    public void paint(Graphics g) {
        	
    // set up CGraphics object
    G = new CGraphics( g );
    w = size().width;
    h = size().height;
    if ( w != h ) w = h; // ensure that w = h  	        		
    G.setScreenRect(  0, 0, w, h  );
    G.insetScreenRect();
    G.setXRange(a,b);
    G.setYRange(c,d);
           
    // display the coordinate axes
    G.abscissa();
    G.ordinate();
       
    // set initial position
    double x = xStart; 
    double y = yStart; 
    
    // Draw a disk at the initial point of the Brownian path 
    G.setColor( Color.red );
    G.fillArc( x, y, 6, 6, 0, 360 );
    
    // Loop to draw Brownian path (XX)
    for( int i = 0; i < n; i++ ) {
    
    	double xx = x + ( R.nextDouble() - 0.5 )*dx; 
    	double yy = y + ( R.nextDouble() - 0.5 )*dy;
    	G.drawLine( x, y, xx, yy ); 
    	x = xx; y = yy; // update position
    	} // end loop
    	
    G.fillArc( x, y, 6, 6, 0, 360 );
    xFinish = x; yFinish = y;
    showStatus( "(" + xStart + ", " + yStart + ") ==> ("+ xFinish + ", " + yFinish + ")");    
	
	} // end paint
		
		
	// set starting position, draw Brownian path, then report 
	// initial and final positions in the status line
	public boolean mouseDown( Event e, int x, int y) {
	
		xStart = G.cx(x); yStart = G.cy(y);
		showStatus( "(x,y) = (" + xStart + ", " + yStart + ")");
		repaint();
		
		return true;
		
	}
}


