Как найти длину отрезка в питоне

Напишите программу, которая вычисляет длину отрезка (т.е. расстояние между двумя точками), заданного двумя значениями x1 и x2 (вещественные числа).

## Длина отрезка по координатам его концов рассчитывается по формуле d = √ (x2-x1)²+ (y2-y1)²), где d — рассчитываемый отрезок, x1, x2 — абсциссы начала и конца отрезка, y1, y2 — ординаты начала и конца отрезка.

Из свободного доступа
Из свободного доступа

Верное решение:

x1, x2 = float(input()), float(input())
print(abs(x2 – x1))

Верное решение:

x1, x2 = map(float,input().split())

d=abs(x1 – x2)

print(d)

Верное решение:

x1, x2 = map(float, input().split())

print(abs(x2 – x1))

Верное решение:

a, b = float(input()), float(input())

print(abs((max(a, b)) – min(a, b)))

Верное решение (в одну строку):

print(abs(float(input())-float(input())))

Верное решение (разминка перед ЕГЭ):

a, b = [float(i) for i in input().split()]

print(abs(a – b))

Из свободного доступа
Из свободного доступа

Python является кроссплатформенным. То есть программа, написанная на Windows, легко запустится на Linux или MacOs.

Skip to content

Задача «Длина отрезка»

Условие

Даны четыре действительных числа: x1y1x2y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). Считайте четыре действительных числа и выведите результат работы этой функции.

Если вы не знаете, как решить эту задачу, то вы, возможно, не изучали в школе теорему Пифагора. Попробуйте прочитать о ней на Википедии.

Решение задачи от разработчиков на Python:

Другая реализация задачи на Python:

Смотреть видео — Задача «Длина отрезка» решение на Python

Делитесь с друзьями ссылкой на ответ и задавайте вопросы в комментариях! 👇

Related Posts

Посмотреть все комментарии
Alex Feel

это один из элементов метода самоидентификации фигур с помощью машинного зрения. здесь неплохо бы вспомнить плоскую систему координат Эйлера в смысле ее модификации для решения задачи распознавания фигур по их границам вне зависимости от их расположения на пиксельной матрице

wpDiscuz

1

Оставьте комментарий! Напишите, что думаете по поводу статьи.x

In this tutorial, we will look at how to calculate the distance between two points in Python with the help of some examples.

If you prefer video over text, check out the following video detailing the steps in this tutorial –

Python - Distance between two points

There are a number of ways to compute the distance between two points in Python. You can compute the distance directly or use methods from libraries like math, scipy, numpy, etc.

We generally refer to the Euclidean distance when talking about the distance between two points. To calculate the Euclidean distance between the points (x1, y1) and (x2, y2) you can use the formula:

Distance between two points in a two-dimensional plane

For example, the distance between points (2, 3) and (5, 7) is 5. Note that the above formula can be extended to n-dimensions.

Euclidean distance between two points in an n-dimensional subspace.

Euclidean distance in Python

Now that we know how the distance between two points is computed mathematically, we can proceed to compute it in Python.

Python has a number of libraries that help you compute distances between two points, each represented by a sequence of coordinates. Before we proceed to use off-the-shelf methods, let’s directly compute the distance between points (x1, y1) and (x2, y2).

# point a
x1 = 2
y1 = 3
# point b
x2 = 5
y2 = 7

# distance b/w a and b
distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
# display the result
print("Distance between points ({}, {}) and ({}, {}) is {}".format(x1,y1,x2,y2,distance))

Output:

Distance between points (2, 3) and (5, 7) is 5.0

You can see that we get the distance between the points (2, 3) and (5, 7) as 5. Note that the above formula works only for points in two dimensions.

Let’s now write a generalized function that can handle points with any number of dimensions.

def get_distance(p, q):
    """ 
    Return euclidean distance between points p and q
    assuming both to have the same number of dimensions
    """
    # sum of squared difference between coordinates
    s_sq_difference = 0
    for p_i,q_i in zip(p,q):
        s_sq_difference += (p_i - q_i)**2
    
    # take sq root of sum of squared difference
    distance = s_sq_difference**0.5
    return distance

# check the function
a = (2, 3, 6)
b = (5, 7, 1)
# distance b/w a and b
d = get_distance(a, b)
# display the result
print(d)

Output:

7.0710678118654755

You can see that we used the function to get distance between two points with three dimensions each. We can now use this function to calculate distances between two points with any dimensions.

Note that the above function can further be improved by using vectorization to calculate the difference between the coordinates.

Euclidean distance using math library

You can use the math.dist() function to get the Euclidean distance between two points in Python. For example, let’s use it the get the distance between two 3-dimensional points each represented by a tuple.

import math

# two points
a = (2, 3, 6)
b = (5, 7, 1)

# distance b/w a and b
d = math.dist(a, b)
# display the result
print(d)

Output:

7.0710678118654755

We get the same value as above.

Euclidean distance using numpy library

The Euclidean distance is equivalent to the l2 norm of the difference between the two points which can be calculated in numpy using the numpy.linalg.norm() function.

import numpy as np

# two points
a = np.array((2, 3, 6))
b = np.array((5, 7, 1))

# distance b/w a and b
d = np.linalg.norm(a-b)
# display the result
print(d)

Output:

7.0710678118654755

We get the same result as above. Note that, here, we pass the difference between points a and b as a numpy array to the the np.linalg.norm() function.

Euclidean distance using scipy library

The scipy library contains a number of useful functions of scientific computation in Python. Use the distance.euclidean() function available in scipy.spatial to calculate the Euclidean distance between two points in Python.

from scipy.spatial import distance

# two points
a = (2, 3, 6)
b = (5, 7, 1)

# distance b/w a and b
d = distance.euclidean(a, b)
# display the result
print(d)

Output:

7.0710678118654755

We get the same result as above. For more on the distance function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5 and pandas version 1.0.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

I want to calculate the length of (any number of) line segments using Python. I used the following code, but I encounter that tuples can not have subtraction as operands. How can I overcome that? I would like to know if I missed any important Python concept.

from itertools import starmap
import math
class Point(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def move(self,dx,dy):
        self.x+=dx
        self.y+=dy


class LineString(object):

    def __init__(self,*args): # A method with any number of arguments, args

        self.args=[Point(*args) for p in args] # A list of Points

    def length(self):
        pairs=zip(self.args, self.args[1:])
        return sum(starmap(distance,pairs))

def distance(p1, p2):
    a = p1.x,p1.y
    b = p2.x,p2.y

    print (math.sqrt((a[0]-b[0])**2-(a[1]-b[1])**2))
    # calculates distance between two given points p1 and p2
    return math.sqrt((a** 2)+ (b** 2))


if __name__ == '__main__':
    # Tests for LineString
    # ===================================
    lin1 = LineString((1, 1), (0, 2))

    assert lin1.length() == sqrt(2.0)

    lin1.move(-1, -1) # Move by -1 and -1 for x and y respectively

    assert lin1[0].y == 0 # Inspect the y value of the start point.
    # Implement this by overloading __getitem__(self, key) in your class.

    lin2 = LineString((1, 1), (1, 2), (2, 2))

    assert lin2.length() == 2.0

    lin2.move(-1, -1) # Move by -1 and -1 for x and y respectively

    assert lin2.length() == 2.0

    assert lin2[-1].x == 1 # Inspect the x value of the end point.

    print ('Success! Line tests passed!')

Занятие 8. Функции и рекурсия

Задача «Длина отрезка»


Условие

Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). Считайте четыре действительных числа и выведите результат работы этой функции.

Если вы не знаете, как решить эту задачу, то вы, возможно, не изучали в школе теорему Пифагора. Попробуйте прочитать о ней на Википедии.


Во всех задачах считывайте входные данные через input() и выводите ответ через print().


Тесты

Входные данные Правильный ответ Что вывела программа Результат
0
0
1
1
1.41421
0
0
1
0
1
3
-2
-1
7
9.84886
0.1
0.1
0.2
0.2
0.141421
-1
-1
-3
-5
4.47214

Добавить комментарий