Search code examples
javareadability

Java Vector Math readability


Let's say you want to do some simple vector calculation:

//this could be C++
MyVectorType position = ...;
MyVectorType velocity = ...;
float dt;
//Here's the expression I want to calculate:
position += dt*velocity;

Now let's say you want to do this in Java. There's no operator overloading - ok, I can live without.

//this still could be C++
MyVectorType position = ...;
MyVectorType velocity = ...;
float dt;
//Here's the expression I want to calculate:
position.add(velocity.times(dt));

I would say it's less readable, but still ok. How should I write the code above in Java? I thought I'd use javax.vecmath:

//my attempt in Java
Vector3f velocity = new Vector3f(...);
Vector3f position = new Vector3f(...);
float dt;
//Here's the expression I want to calculate - three lines.
Vector3f deltaPosition = new Vector3f(velocity);
deltaPosition.scale(dt);
position.add(deltaPosition);

Does it really require these three lines to perform such a simple operation? For people being used to reading mathematical expressions I think this is a pain, especially as the operations become more complex. Also, writing such expressions is not really a pleasure.

Am I missing something? Or is there another vector math package that leads to more readable code?


Solution

  • The javax.vecmath package is, unfortunately, kind of clunky. You might want to take a look at JAMA from NIST. It's a matrix package, not a vector package (doesn't have cross product, for example), but at least with that package, you can chain operations together on a single line:

    double[][] array = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}}; 
    Matrix A = new Matrix(array); 
    Matrix b = Matrix.random(3,1); 
    Matrix x = A.solve(b); 
    Matrix Residual = A.times(x).minus(b); 
    

    You can do a lot of vector arithmetic by treating vectors as 1xN matrices.

    NIST has also posted a page of links to other Java numerics packages where you might find something that's a closer match to your needs if JAMA isn't quite right.