Distance Between Points

Synopsis

Compute the distance between two 3D points. This can easily be extended to ND by changing the constant Dimension.

Results

Output:

Dist: 1.73205
Dist2: 3

Code

C++

#include "itkPoint.h"
#include "itkMath.h"

#include <iostream>

int
main(int, char *[])
{
  constexpr unsigned int Dimension = 3;
  using CoordType = double;

  using PointType = itk::Point<CoordType, Dimension>;

  PointType p0;
  p0[0] = 0.0;
  p0[1] = 0.0;
  p0[2] = 0.0;

  PointType p1;
  p1[0] = 1.0;
  p1[1] = 1.0;
  p1[2] = 1.0;

  PointType::RealType dist = p0.EuclideanDistanceTo(p1);
  std::cout << "Dist: " << dist << std::endl;

  if (dist != p1.EuclideanDistanceTo(p0))
  {
    std::cerr << "p0.EuclideanDistanceTo(p1) != p1.EuclideanDistanceTo(p0)" << std::endl;
    return EXIT_FAILURE;
  }

  if (p1.EuclideanDistanceTo(p1) != 0.)
  {
    std::cerr << "p1.EuclideanDistanceTo(p1) != 0." << std::endl;
    return EXIT_FAILURE;
  }

  PointType::RealType dist2 = p0.SquaredEuclideanDistanceTo(p1);
  std::cout << "Dist2: " << dist2 << std::endl;

  if (std::abs(dist2 - dist * dist) < itk::Math::eps)
  {
    std::cerr << "dist2 != dist * dist" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Classes demonstrated