# Monte Carlo Java Calculating the value of pi

Monte Carlo. Can’t get enough of it,  so here’s the Java version of the program that calculates value of pi with Monte Carlo.

Have done it in Fortran using pgplot as the GUI engine. You can see it action here.

See the Java applet in action

One thing though, the Java program takes more time to converge on the  value of pi than the Fortran. Maybe my rusty Java program.

#### Neutron Collisions, Stanislaw Ulam , Solitares and my Pgplot practice.

Java code for calculating the value of pi using Monte Carlo.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MonteCarlo extends JApplet implements Runnable  {

private static final long serialVersionUID = 1L;

int width,height,pcnt=1,pin=1;
double diff;
int ranx,rany;
Image offscreenImage;
Graphics offscreenGraphics;
int xbar=2,ybar=2,barwid,barheigt=21;
double bartop =3.04;
double barbot = 3.21;
double barmid = 3.14;
double barval;
int line;

public void init(){

width= getSize().width;
height = getSize().height;
setBackground(Color.black);
barwid = width -4;
offscreenImage = createImage(width,height);
offscreenGraphics = offscreenImage.getGraphics();

}

public void start() {
if ( t == null ) {
t = new Thread( this );
t.start();
}
else {
synchronized( this ) {
notify();
}
}
}
}

public void stop() {
}
public void paint(Graphics g){

int x0,y0,tick=1;

x0=getX()+(int)(width/2.0);
y0=getY()+(int)((height+25)/2.0);

offscreenGraphics.setColor(Color.green);
offscreenGraphics.drawLine(ranx, rany, ranx, rany);
pcnt++;

offscreenGraphics.setColor(Color.yellow);
offscreenGraphics.drawLine(ranx, rany, ranx, rany);
pival=4.0 * (double)pin/pcnt;

pin++;
}
diff=pival-3.14159265;

offscreenGraphics.setColor(Color.gray);

offscreenGraphics.fillRect(xbar, ybar, barwid, barheigt);
offscreenGraphics.setColor(Color.white);
offscreenGraphics.drawString(""+bartop, xbar, ybar+8);
offscreenGraphics.drawString(""+barbot, barwid-22, ybar+8);
offscreenGraphics.drawString(""+barmid, (barwid-22)/2, ybar+8);

barval = ((barwid-xbar-22)/(barbot-bartop))*(pival-bartop)  ;
line=(int) barval;
offscreenGraphics.setColor(Color.orange);
offscreenGraphics.drawLine(line, ybar, line,barheigt);

g.drawImage(offscreenImage, 0, 0, this);
}

public void run() {
try {
while(true){
repaint();
t.sleep(0);

}
} catch (InterruptedException e) {
// TODO: handle exception
}

}

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

}

private void pause(int pauseLength) {
try { Thread.sleep(pauseLength); } catch (InterruptedException e) {}
}

}