{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Weekly exercise 9: Finding the intersection of line segments\n", "\n", "Given two line segments in $ \\mathbb{R}^2 $ with endpoint\n", "coordinates as\n", "\n", "$$\n", "(x^1_1,y^1_1),(x^1_2,y^1_2) \\text{ and } (x^2_1,y^2_1),(x^2_2,y^2_2),\n", "$$\n", "\n", "where superscripts indicate the segment, subscripts indicate beginning\n", "and end of the line, find whether the segments intersect, and if so,\n", "what is the intersection point." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Method\n", "\n", "Let intersection be given by $ (x_0,y_0) $, and introduce two more\n", "variables $ t_1 $ and $ t_2 $ that equal to the distance from\n", "the starting points $ (x^1_1,y^1_1) $ and $ (x^2_1,y^2_1) $ to\n", "the intersection point, relative to the corresponding segment lengths.\n", "Then we can write the following system of equations\n", "\n", "$$\n", "\\begin{eqnarray*}\n", "(x^1_2 - x^1_1) \\cdot t_1 &=& x_0 - x^1_1 \\\\\n", "(x^2_2 - x^2_1) \\cdot t_2 &=& x_0 - x^2_1 \\\\\n", "(y^1_2 - y^1_1) \\cdot t_1 &=& y_0 - y^1_1 \\\\\n", "(y^2_2 - y^2_1) \\cdot t_2 &=& y_0 - y^2_1 \\\\\n", "\\end{eqnarray*}\n", "$$\n", "\n", "In matrix notation $ Az=b $ where\n", "\n", "$$\n", "A=\n", "\\begin{pmatrix}\n", "x^1_2 - x^1_1 & 0 & -1 & 0 \\\\\n", "0 & x^2_2 - x^2_1 & -1 & 0 \\\\\n", "y^1_2 - y^1_1 & 0 & 0 & -1 \\\\\n", "0 & y^2_2 - y^2_1 & 0 & -1 \\\\\n", "\\end{pmatrix},\\;\\;\n", "b=\\begin{pmatrix}\n", "-x^1_1\\\\\n", "-x^2_1\\\\\n", "-y^1_1\\\\\n", "-y^2_1\\\\\n", "\\end{pmatrix},\\;\\;\n", "z=(t_1,t_2,x_0,y_0)\n", "$$\n", "\n", "After solving the system, we can check $ t_1 $ and $ t_2 $\n", "\n", "- If both belong to $ [0,1] $, the intersection point exists and is given by the computed $ (x_0,y_0) $ \n", "- Otherwise, it the segments do not intersect " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Task\n", "\n", "Write a function that takes the coordinates of the two line segments as input, and outputs the coordinates of the intersection point, if it exists, and None otherwise.\n", "\n", "Write several tests to check that your function works correctly in both cases when lines do and do not intersect." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide-output": false }, "outputs": [], "source": [ "# your code here" ] } ], "metadata": { "date": 1627475014.565591, "filename": "exercise09.rst", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" }, "title": "Weekly exercise 9: Finding the intersection of line segments" }, "nbformat": 4, "nbformat_minor": 4 }