It's easy to use the mathematical formula to find distance between any two points in 3D space which is:√((x2-x1)^2 )+(y2-y1)^2+(z2-z1)^2
And it's pretty easy to calculate for finding distance between any two points in space where each point has (x, y z) coordinates in 3D-space.
My question, extends this formula to a large scale where I'm facing optimization hiccups. What I did was create a simple Vector
class and use this formula coded in C++ to calculate the distance.
What if there are a 1000 points? How do I go about it? I'm thinking using a simple std::vector
to store these 3D points won't be optimized way of calculating the distance between these 1000 points.
There are different level of optimization, each depends on actual situation.
On implementation level, you want to layout the data in a friendly way to the processor. ie.
This may give you up to 10% boost.
On algorithm Level, you may want to think again why do you need distances of every point in core loop
EDIT: Opps in 3D space the complexity grows to same level with Cartesian coordinate, ignore point 3.
GPU Consideration
While 1000 points are too few to trade for the overhead, you may still consider off-load the work to GPU if you have a lot more points in future.
Here is a version of a Vector3 class object that may help you.
Vector3.h
Vector3.cpp
GeneralMath.h
GeneralMath.cpp
If you take a notice at the Vector3 class object it has 2 methods that returns the length of the vector. One uses the sqrt() which will give the absolute length but is more expensive to use. The second method length2() does not use the sqrt() and returns the relative length which is inexpensive. This same exact concept can be applied to finding distances between two points! I hope this class helps you. If you need to know the exact length or distance then yes use the sqrt() version. When it comes to comparisons between multiple points or vectors then the comparison truth table between A & B is the same using either method so it is optimal to use the 2nd version of this function.