Calculate distance and slope of a line in Python

Calculate distance and slope of a line in Python

In this article, we'll explore how to implement a Line class in Python that calculates the distance and slope between two points. We'll also discuss some possible optimizations to make the code more efficient and maintainable.

The mathematical equation to calculate the distance between two points (x1, y1) and (x2, y2) is:

distance = ((x2 - x1)^2 + (y2 - y1)^2)^(1/2)

The mathematical equation to calculate the slope of a line passing through two points (x1, y1) and (x2, y2) is:

slope = (y2 - y1)/(x2 - x1)

The slope represents the steepness of the line, which is the ratio of the change in the y-coordinates (vertical change) to the change in the x-coordinates (horizontal change) between two points.

Here is a simple Python code that calculates and prints the distance and slope of the line based on provided coordinates.

class Line:

    def __init__(self,coor1,coor2):
        x1,y1 = coor1
        x2,y2= coor2
        self.x1= x1
        self.y1= y1
        self.x2 = x2
        self.y2 = y2

    def distance(self):
        return(((self.x2-self.x1)**2)+((self.y2-self.y1)**2))**0.5

    def slope(self):
        return (self.y2 - self.y1)/(self.x2-self.x1)


coordinate1 = (4,2)
coordinate2 = (10,12)

li = Line(coordinate1,coordinate2)

print(f"Distance is: {li.distance()}")
print(f"Slope is: {li.slope()}")

Once we run this code we see the result of the calculation.

This is a simple implementation of a Line class that calculates the distance and slope between two points. One possible optimization could be to use the math.sqrt() function instead of raising the value to the power of 0.5 to calculate the distance.

Here's the updated code:

import math

class Line:

    def __init__(self,coor1,coor2):
        x1,y1 = coor1
        x2,y2= coor2
        self.x1= x1
        self.y1= y1
        self.x2 = x2
        self.y2 = y2

    def distance(self):
        return math.sqrt((self.x2 - self.x1) ** 2 + (self.y2 - self.y1) ** 2)

    def slope(self):
        return (self.y2 - self.y1)/(self.x2 - self.x1)


coordinate1 = (4,2)
coordinate2 = (10,12)

li = Line(coordinate1,coordinate2)

print(li.distance())
print(li.slope())