Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Vec2D {
- final double x, y;
- Vec2D(double x, double y) {
- this.x = x;
- this.y = y;
- }
- Vec2D add(Vec2D other) {
- return new Vec2D(x + other.x, y + other.y);
- }
- Vec2D sub(Vec2D other) {
- return new Vec2D(x - other.x, y - other.y);
- }
- Vec2D mul(double d) {
- return new Vec2D(x * d, y * d);
- }
- Vec2D div(double d) {
- return new Vec2D(x / d, y / d);
- }
- double length() {
- return Math.sqrt(x*x + y*y);
- }
- }
- class Entity {
- Vec2D vel;
- double mass;
- Entity(double mass, Vec2D vel) {
- this.mass = mass;
- this.vel = vel;
- }
- void changeReferenceFrame(Vec2D vel) {
- this.vel = this.vel.sub(vel);
- }
- Vec2D momentum() {
- return vel.mul(mass);
- }
- double kinEnergy() {
- double v = vel.length();
- return 0.5 * mass * v * v;
- }
- //updates velocities and returns energy dissipated in collision
- double collideInelastic(Entity other) {
- Vec2D newVel = this.momentum().add(other.momentum()).div(mass + other.mass);
- double energyBefore = kinEnergy() + other.kinEnergy();
- this.vel = newVel;
- other.vel = newVel;
- double energyAfter = kinEnergy() + other.kinEnergy();
- return energyBefore - energyAfter;
- }
- public Entity clone() {
- return new Entity(mass, vel);
- }
- }
- public class Energy {
- static double collideInRandomReferenceFrame(Entity e1, Entity e2) {
- Vec2D ref = new Vec2D(Math.random() * 100, Math.random() * 100);
- e1 = e1.clone();
- e2 = e2.clone();
- e1.changeReferenceFrame(ref);
- e2.changeReferenceFrame(ref);
- return e1.collideInelastic(e2);
- }
- public static void main(String[] args) {
- Entity e1 = new Entity(10, new Vec2D(35, 45));
- Entity e2 = new Entity(23, new Vec2D(-20, -17));
- for(int i = 0; i < 100; i++) {
- double energy = collideInRandomReferenceFrame(e1, e2);
- System.out.println(energy);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement