Skip to main content

Command Palette

Search for a command to run...

Calculate distance and slope of a line in Python

Updated
2 min read
Calculate distance and slope of a line in Python
A

Currently I am pursuing M Tech in Artificial intelligence and Machine Learning. As a developer, I possess expertise in an array of technologies ranging from Magento, Python, Artificial Intelligence and Machine Learning. My passion for technology and coding inspires me to continuously learn and innovate in my field.

With this blog, I aim to share my knowledge and experience with fellow developers in the community, helping them stay updated with the latest trends and techniques in the industry.

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())

More from this blog

Python, Machine Learning & Data Science

13 posts

Python, Machine Learning & Data Science Enthusiast