Wednesday, September 30, 2009

Homework 4: Vectors

A vector in 2-dimensional space, as used in math an physics, is just a pair of numbers: delta-x and delta-y. We call these numbers the components of the vector. Vectors are drawn as arrows. For example, the vector in the figure has a delta-x of 2, and a delta-y of 3. In physics, vectors represent forces. Adding two vectors represents placing those two forces on an object. The resulting force is just the addition of the two vectors. You can add two vectors by simply adding their delta-x and delta-y values. That is, the new delta-x is the sum of the delta-x of the two other vectors.
More formally, for vectors v1 and v2 with components v1.dx, v1.dy and v2.dx, v2.dy, we can define various vector operations:
  • Vector addition: v1 + v2 = v3 is implemented as v3.dx = v1.dx + v2.dx and v3.dy = v1.dy + v2.dy
  • Vector subtraction: v1 - v2 = v3 is implemented as v3.dx = v1.dx - v2.dx and v3.dy = v1.dy - v2.dy
  • Vector scalar multiplication: v1 * c = v2 where c is a constant is implemented as v2.dx = v1.dx * c and v2.dy = v1.dy * c
  • Vector magnitude of v1 is a number equal to the square root of v1.dx*v1.dx + v1.dy*v1.dy.
  • A vector v1 can be normalized by setting v1.dx = v1.dx / v1.magnitude and v1.dy = v1.dy / v1.magnitude
For this homework you will implement a Vector class that has the following data members:
  1. dx, a double
  2. dy, a double
and the following methods:
  1. A constructor that takes as argument two numbers which will become the delta-x and delta-y
  2. public void addVector(Vector otherVector) which adds otherVector to this vector
  3. public void subtractVector(Vector otherVector) which subtracts otherVector from this vector
  4. public void multiply(int a) does a scalar multiplication of this vector by a
  5. public double getMagnitude() returns the magnitude of this vector.
  6. public void normalize() normalizes this vector.
  7. public String toString() returns a printable version of the vector.

You must also implement a main function that tests all your methods to make sure they are correct.

One very important rule you must follow is Don't Repeat Yourself (DRY) which means that:

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system ”
In other words, any value that can be calculated from data member values must be calculated from data members values. This homework is due Tuesday, October 6 @ noon.

1 comment:

Xu Sun said...

If you are not very clear about class and object, you can go to the following website:

Read fundamental concepts and features please.