# Laplace.java

Below is the syntax highlighted version of Laplace.java from §9.8 Data Analysis.

```/******************************************************************************
*  Compilation:  javac Laplace.java
*  Execution:    java Laplace N x y
*
*  Estimate the potential of a point (x, y) in an N-by-N region where
*  the horizontal boundaries have potential 10 and the vertical boundaries
*  have potential 5.
*
*  Simulate 1,000,000 random walks until they reach the boundary and use
*  the average potential to estimate the potential at (x, y).
*
*  java Laplace 10 5 8
*  Potential of (5, 8) = 6.5365
*
*  java Laplace 10 5 8
*  Potential of (5, 8) = 6.53945
*
*  java Laplace 10 5 8
*  Potential of (5, 8) = 6.5378
*
******************************************************************************/

public class Laplace {

public static void main(String[] args) {
int TRIALS = 100000;                   // number of trials
int N = Integer.parseInt(args);     // number of steps
int X = Integer.parseInt(args);     // starting x value
int Y = Integer.parseInt(args);     // starting y value
int potential = 0;                     // sum of potentials

for (int i = 0; i < TRIALS; i++) {
int x = X, y = Y;
while (x > 0 && x < N && y > 0 && y < N) {
double r = Math.random();           // between 0.0 and 1.0
if      (r < 0.25) x++;
else if (r < 0.50) x--;
else if (r < 0.75) y++;
else               y--;
}
if (x == 0 || x == N) potential += 10;
else potential +=  5;

}

StdOut.println("Potential of (" + X + ", " + Y + ") = " + 1.0 * potential / TRIALS);
}
}
```

Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.