1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
#include <iostream>
#include <cmath>
using namespace std;
struct Point{ double x, y; };
struct Line{ Point a, b; };
const double EPS = 1.0e-10;
//======================================================================
bool intersectionFromSlopeIntercept( double m1, double c1, double m2, double c2, Point &r )
{
r = Point{ 0, 0 };
if ( abs( m1 - m2 ) < EPS ) return false; // Slopes are equal
r.x = ( c2 - c1 ) / ( m1 - m2 );
r.y = m1 * r.x + c1;
return true;
}
//======================================================================
bool intersectionFromLines( Line L, Line M, Point &r )
{
r = Point{ 0, 0 };
double crossProduct = ( M.b.x - M.a.x ) * ( L.b.y - L.a.y ) - ( M.b.y - M.a.y ) * ( L.b.x - L.a.x );
if ( abs( crossProduct ) < EPS ) return false; // Slopes are equal (cross product of direction vectors is 0)
// Fractional distance from a to b along line M by ratio of projections
double fraction = ( ( L.b.x - M.a.x ) * ( L.b.y - L.a.y ) - ( L.b.y - M.a.y ) * ( L.b.x - L.a.x ) )
/ crossProduct;
r.x = M.a.x + fraction * ( M.b.x - M.a.x );
r.y = M.a.y + fraction * ( M.b.y - M.a.y );
return true;
}
//======================================================================
int main()
{
// Line 1
double m1 = 1.03297, c1 = -0.758242;
Point La{ 0.0, -0.758242 }, Lb{ 1.0, 0.274728 };
Line L{ La, Lb };
// Line 2
double m2 = 1.0, c2 = 5.0;
Point Ma{ 0.0, 5.0 }, Mb{ 1.0, 6.0 };
Line M{ Ma, Mb };
Point r;
cout << "Line 1 is y = " << m1 << "x " << ( c1 > 0 ? "+" : "" ) << c1 << '\n';
cout << "Line 2 is y = " << m2 << "x " << ( c2 > 0 ? "+" : "" ) << c2 << '\n';
cout << "Slope/y-intercept method:\n";
if ( intersectionFromSlopeIntercept( m1, c1, m2, c2, r ) )
{
cout << "x = " << r.x << '\n';
cout << "y = " << r.y << '\n';
}
else
{
cout << "No intersection" << '\n';
}
cout << "Line points method:\n";
if ( intersectionFromLines( L, M, r ) )
{
cout << "x = " << r.x << '\n';
cout << "y = " << r.y << '\n';
}
else
{
cout << "No intersection" << '\n';
}
}
|