Auf ein Quadrat mit der Seitenlänge 1 werden Zufallspunkte gestreut, deren Koordinaten mit zwei Zufallszahlen zwischen 0 und 1 bestimmt sind. Aus dem Verhältnis der Zahl der Punkte, die innerhalb des Viertelkreises liegen zu allen Punkten, kann die Zahl PI berechnet werden. |
![]() |
// MonteCarlo.java, Berechnung der Zahl PI import ch.aplu.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; class MonteCarlo extends GPanel { private int n; // Anzahl Versuche private int hits; // Anzahl Treffer private double pi; private JTextField nTextField = new JTextField(6); private JLabel nLabel = new JLabel("Anzahl Tropfen"); private JButton goButton = new JButton("go"); MonteCarlo() { goButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { init(); n = Integer.parseInt(nTextField.getText()); simulate(); pi = 4 * (double)hits / n ; color(Color.black); pos( 0, -0.2 ); text("Die Zahl PI ist " + pi); } }); add(nLabel); add(nTextField); add(goButton); validate(); } private void init() { window(-0.5, 1.5, -0.5, 1.5); clear(); pos(0.5, 0.5); rectangle(1, 1); pos(0, 0); arc(1, 0, 90); } private void simulate() { double zx, zy; hits = 0; for (int i = 0; i < n; i++) { zx = Math.random(); zy = Math.random(); if (zx * zx + zy * zy < 1) { hits = hits + 1; color(Color.red); } else color(Color.green); point(zx, zy); } } public static void main(String[] args) { new MonteCarlo(); } } |