KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > physics > GravityField


1 package JSci.physics;
2
3 public class GravityField {
4         private final ClassicalParticle3D source;
5
6         /**
7         * Constructs the gravitational field of a particle.
8         */

9         public GravityField(ClassicalParticle3D p) {
10                 source = p;
11         }
12         /**
13         * Returns the potential energy of a particle in this field.
14         */

15         public double energy(ClassicalParticle3D p) {
16                 final double dx = p.x-source.x;
17                 final double dy = p.y-source.y;
18                 final double dz = p.z-source.z;
19                 final double r = Math.sqrt(dx*dx+dy*dy+dz*dz);
20                 return -PhysicalConstants.GRAVITATION*source.getMass()*p.getMass()/r;
21         }
22         /**
23         * Creates the force acting on a particle in this field.
24         */

25         public Force3D createForce(ClassicalParticle3D p) {
26                 return new Force(p);
27         }
28         private class Force extends Force3D {
29                 private final ClassicalParticle3D p;
30                 private double x, y, z;
31                 public Force(ClassicalParticle3D p) {
32                         this.p = p;
33                 }
34                 private void calculate() {
35                         final double dx = p.x-source.x;
36                         final double dy = p.y-source.y;
37                         final double dz = p.z-source.z;
38                         final double rr = dx*dx+dy*dy+dz*dz;
39                         final double r = Math.sqrt(rr);
40                         final double magnitude = -PhysicalConstants.GRAVITATION*source.getMass()*p.getMass()/rr;
41                         x = magnitude*dx/r;
42                         y = magnitude*dy/r;
43                         z = magnitude*dz/r;
44                 }
45                 public double getXComponent(double t) {
46                         calculate();
47                         return x;
48                 }
49                 public double getYComponent(double t) {
50                         calculate();
51                         return y;
52                 }
53                 public double getZComponent(double t) {
54                         calculate();
55                         return z;
56                 }
57         }
58 }
59
60
Popular Tags