7
\$\begingroup\$

I wrote the following implementation of a Vector in Java. I was wondering what you folks thought of it.

package space;
public class SpaceVector {
 private final double x;
 private final double y;
 private final double z;
 public SpaceVector(double x, double y, double z){
 this.x = x;
 this.y = y;
 this.z = z;
 }
 public SpaceVector minus(SpaceVector o) {
 return new SpaceVector(x - s.x, y - s.y, z - s.z);
 }
 public double dot(SpaceVector o) {
 return x * o.x + y * o.y + z * o.z;
 }
 public double abs() {
 return Math.sqrt(x * x + y * y + z * z);
 }
 public SpaceVector cross(SpaceVector o) {
 double i, j, k;
 i = y * o.z - z * o.y;
 j = -(x * o.z - z * o.x);
 k = x * o.y - y * o.x;
 return new SpaceVector(i, j, k);
 }
}
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Feb 25, 2015 at 2:22
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

Within a mathematical tradition,

  • minus is an unary operator, as in

    public minus() {
     return new SpaceVector(-x, -y, -z);
    }
    
  • A vector-by-scalar multiplication

    public scale_by(double scalar)
    

    is expected (notice that minus is actually scale_by(-1)).

  • Vector addition

    public add(SpaceVector other)
    

    is expected.

  • abs is usually called norm.

answered Feb 25, 2015 at 6:32
\$\endgroup\$
4
\$\begingroup\$

Personally, I find something like this really hard to read, because it contains so many one letter variables:

 i = y * o.z - z * o.y;
 j = -(x * o.z - z * o.x);
 k = x * o.y - y * o.x;

I would prefer it like this:

 double i = this.y * vector.z - this.z * vector.y;
 double j = this.z * vector.x - this.x * vector.z;
 double k = this.x * vector.y - this.y * vector.x;

You can omit the this if you don't like it, but I think that the vector really helps. Note also that I changed the second line slightly for more readability, and that I declared the variables when assigning values to them, saving a line and increasing readability.

Misc

  • minus(SpaceVector o) should be minus(SpaceVector s)
  • generally, this is called Vector3d (with the d standing for double), which is a lot more expressive than SpaceVector.
answered Feb 25, 2015 at 9:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.