Distance from a point to a straight line C++

I have the following code for finding the distance between a point and a straight line:

template<typename T>
using point_t = std::pair<T, T>;

template<typename T>
using line_segment_t = std::pair<point_t<T>, point_t<T>>;

template<typename CoordinateType>
double get_distance_between_point_and_line_segment(const 
line_segment_t<CoordinateType>& line_segment, const point_t<CoordinateType>& point) noexcept
{ 
    const CoordinateType x = std::get<X_COORDINATE>(point);
    const CoordinateType y = std::get<Y_COORDINATE>(point);

    const CoordinateType x1 = std::get<X_COORDINATE>(line_segment.first);
    const CoordinateType y1 = std::get<Y_COORDINATE>(line_segment.first);

    const CoordinateType x2 = std::get<X_COORDINATE>(line_segment.second);
    const CoordinateType y2 = std::get<Y_COORDINATE>(line_segment.second);

    const double double_area = abs((y2-y1)*x - (x2-x1)*y + x2*y1 - y2*x1);
    const double line_segment_length = sqrt((x2*x2 - x1*x1) + (y2*y2 - y1*y1));
    return double_area / line_segment_length;
}

It would seem that everything is fine, but if I, for example, give the line { (5;1), (1;5) } as input, then when calculating its length, I get 0, and therefore further division by zero... In my situation, I can't check for the result line_segment_length and throw say an exception if the length is zero. I need to know at least the approximate length between the point and the segment when line_segment_length became zero. How can all this be done implement it?

Author: Kromster, 2019-04-16

1 answers

As @AlexKrass correctly said, you have an error in the line

const double line_segment_length = sqrt((x2*x2 - x1*x1) + (y2*y2 - y1*y1));

The length (Euclidean norm) is the root of the sum of the squares of the coordinate differences. Must be

const double line_segment_length = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));

Or, after opening the brackets

const double line_segment_length = sqrt(x2*x2 - 2*x2*x1 + x1*x1 + y2*y2 - 2*y2*y1 + y1*y1);
 4
Author: Герман Борисов, 2019-04-16 11:32:26