Advertisement
Guest User

collision energy

a guest
May 11th, 2014
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. class Vec2D {
  2.     final double x, y;
  3.     Vec2D(double x, double y) {
  4.         this.x = x;
  5.         this.y = y;
  6.     }
  7.    
  8.     Vec2D add(Vec2D other) {
  9.         return new Vec2D(x + other.x, y + other.y);
  10.     }
  11.     Vec2D sub(Vec2D other) {
  12.         return new Vec2D(x - other.x, y - other.y);
  13.     }
  14.     Vec2D mul(double d) {
  15.         return new Vec2D(x * d, y * d);
  16.     }
  17.     Vec2D div(double d) {
  18.         return new Vec2D(x / d, y / d);
  19.     }
  20.     double length() {
  21.         return Math.sqrt(x*x + y*y);
  22.     }
  23. }
  24.  
  25. class Entity {
  26.     Vec2D vel;
  27.     double mass;
  28.    
  29.     Entity(double mass, Vec2D vel) {
  30.         this.mass = mass;
  31.         this.vel = vel;
  32.     }
  33.    
  34.     void changeReferenceFrame(Vec2D vel) {
  35.         this.vel = this.vel.sub(vel);
  36.     }
  37.    
  38.     Vec2D momentum() {
  39.         return vel.mul(mass);
  40.     }
  41.    
  42.     double kinEnergy() {
  43.         double v = vel.length();
  44.         return 0.5 * mass * v * v;
  45.     }
  46.    
  47.     //updates velocities and returns energy dissipated in collision
  48.     double collideInelastic(Entity other) {
  49.         Vec2D newVel = this.momentum().add(other.momentum()).div(mass + other.mass);
  50.         double energyBefore = kinEnergy() + other.kinEnergy();
  51.         this.vel = newVel;
  52.         other.vel = newVel;
  53.         double energyAfter = kinEnergy() + other.kinEnergy();
  54.         return energyBefore - energyAfter;
  55.     }
  56.    
  57.     public Entity clone() {
  58.         return new Entity(mass, vel);
  59.     }
  60. }
  61.  
  62. public class Energy {
  63.     static double collideInRandomReferenceFrame(Entity e1, Entity e2) {
  64.         Vec2D ref = new Vec2D(Math.random() * 100, Math.random() * 100);
  65.         e1 = e1.clone();
  66.         e2 = e2.clone();
  67.         e1.changeReferenceFrame(ref);
  68.         e2.changeReferenceFrame(ref);
  69.         return e1.collideInelastic(e2);
  70.     }
  71.    
  72.     public static void main(String[] args) {
  73.         Entity e1 = new Entity(10, new Vec2D(35, 45));
  74.         Entity e2 = new Entity(23, new Vec2D(-20, -17));
  75.        
  76.         for(int i = 0; i < 100; i++) {
  77.             double energy = collideInRandomReferenceFrame(e1, e2);
  78.             System.out.println(energy);
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement