Gianni Spear
Gianni Spear

Reputation: 8000

Python: Does a module exist which already find an angle and the distance between two points?

First of all, I apologize to post this easy question. Probably there is a module to compute angle and distance between two points.

Upvotes: 2

Views: 4439

Answers (2)

unutbu
unutbu

Reputation: 880787

Given

enter image description here

you could compute the angle, theta, and the distance between A and B with:

import math
def angle_wrt_x(A,B):
    """Return the angle between B-A and the positive x-axis.
    Values go from 0 to pi in the upper half-plane, and from 
    0 to -pi in the lower half-plane.
    """
    ax, ay = A
    bx, by = B
    return math.atan2(by-ay, bx-ax)

def dist(A,B):
    ax, ay = A
    bx, by = B
    return math.hypot(bx-ax, by-ay)

A = (560023.44957588764, 6362057.3904932579)
B = (560036.44957588764, 6362071.8904932579)
theta = angle_wrt_x(A, B)
d = dist(A, B)
print(theta)
print(d)

which yields

0.839889619638  # radians
19.4743420942

(Edit: Since you are dealing with points in a plane, its easier to use atan2 than the dot-product formula).

Upvotes: 7

zch
zch

Reputation: 15278

Sure, math module has atan2. math.atan2(y, x) is an angle (0, 0) to (x, y).

Also math.hypot(x, y) is distance form (0, 0) to (x, y).

Upvotes: 4

Related Questions