Equipotential.java
This is the syntax highlighted version of Equipotential.java
from 3.2 Creating Data Types of
Introduction to Computer Science by
Robert Sedgewick and Kevin Wayne.
public class Equipotential {
public static void main(String[] args) {
int SIZE = 600; // size of window
double RADIUS = 500E-12; // real size (m)
double eps = RADIUS / SIZE; // real size of 1 pixel
double e = 1.60217733E-19; // elementary charge (C)
int N = Integer.parseInt(args[0]); // number of charges
Charge[] charges; // the N random charges
// N random charges
charges = new Charge[N];
for (int i = 0; i < N; i++) {
double x = Math.random() * RADIUS;
double y = Math.random() * RADIUS;
double k = e;
if (Math.random() < 0.5) k = -e;
charges[i] = new Charge(x, y, k);
}
StdDraw.create(SIZE, SIZE);
// draw equipotential lines; compute potential and field strength at (x, y)
for (int ix = 0; ix < SIZE; ix++) {
for (int iy = 0; iy < SIZE; iy++) {
double x = ix * RADIUS / SIZE;
double y = iy * RADIUS / SIZE;
// electric potential V at (x, y)
double V = 0.0;
for (int i = 0; i < N; i++) {
V += charges[i].potential(x, y);
}
// vector field (Ex, Ey) at (x, y) and total strength E
double Ex = 0.0, Ey = 0.0;
for (int i = 0; i < N; i++) {
Ex += charges[i].fieldX(x, y);
Ey += charges[i].fieldY(x, y);
}
double E = Math.sqrt(Ex*Ex + Ey*Ey);
// draw if potential is < 1/2 pixel from a multiple of 5V (since E = grad V)
// if ((Math.abs(V) % 5) < 1.0 * E * eps) {
if ((V - Math.floor(V/5) * 5) < 1.0 * E * eps) {
StdDraw.go(ix, iy);
StdDraw.spot(0);
}
}
}
StdDraw.show();
StdDraw.save("equipotential.png");
}
}
Last updated: Fri Jul 30 16:00:04 EDT 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.