Representing Points and Lines in Python
Swipe to show menu
In geometric modelling, you often need to represent basic geometric objects like points and lines in a way that is both efficient and easy to work with. In Python, the most straightforward way to represent a point in two-dimensional space is as a tuple containing its x and y coordinates. For example, a point at coordinates (2, 3) can be written as (2, 3).
A line segment, which connects two points, can be represented as a pair of such tuples. This means a line from point A to point B is simply the pair (A, B), where each is a tuple of coordinates. This approach leverages Python's built-in data structures and keeps your code clean and readable.
Once you have points and lines represented in this way, you can perform geometric calculations. A common operation is finding the distance between two points. The distance formula in two dimensions is derived from the Pythagorean theorem and is given by sqrt((x2 - x1)^2 + (y2 - y1)^2). Python's math module provides the sqrt function to make this calculation straightforward.
1234567891011121314151617import math # Define two points as tuples point_a = (2, 3) point_b = (7, 11) # Define a line as a pair of points line_ab = (point_a, point_b) # Calculate the distance between point_a and point_b def distance(p1, p2): dx = p2[0] - p1[0] dy = p2[1] - p1[1] return math.sqrt(dx * dx + dy * dy) dist = distance(point_a, point_b) print("Distance between A and B:", dist)
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat