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);
}
}
2 Answers 2
Within a mathematical tradition,
minus
is an unary operator, as inpublic minus() { return new SpaceVector(-x, -y, -z); }
A vector-by-scalar multiplication
public scale_by(double scalar)
is expected (notice that
minus
is actuallyscale_by(-1)
).Vector addition
public add(SpaceVector other)
is expected.
abs
is usually callednorm
.
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 beminus(SpaceVector s)
- generally, this is called
Vector3d
(with thed
standing fordouble
), which is a lot more expressive thanSpaceVector
.