I have a vector class (2D mathematical vector) with float
s as its components.
For some intermediate calculations I have the choice of using doubles. Should I use the intermediate double precision as long as possible, only casting to float at the end, or is it better to cast any doubles back to floats as soon as possible?
For example, here are two possible implementations of the vector normalization.
First, keeping the double for all calculations:
public class Vector2f {
private float x;
private float y;
....
public Vector2f normalize() {
double length = Math.sqrt((x * x) + (y * y));
return new Vector2f(
(float) (x / length),
(float) (y / length)
);
}
}
Second, converting to float immediately:
public Vector2f normalize() {
float length = (float) Math.sqrt((x * x) + (y * y));
return new Vector2f(
x / length,
y / length
);
}