Python: find a x,y coordinate for a given point B using the distance from the point A (x0, y0) and the angle

StackOverflow https://stackoverflow.com/questions/23280636

سؤال

Is there a function already implemented in Python to find the X, Y of a point B from a point A (x0, Y0) using a given angle expressed in degrees (°)?

from math import cos, sin

def point_position(x0, y0, dist, theta):
    return dist*sin(theta), dist*cos(theta)

where x0 = x coordinate of point A, y0 = y coordinate of point A, dist = distance between A and B, theta = angle (°) of the point B respect the North (0°) measured by a compass

هل كانت مفيدة؟

المحلول

You just need a function that converts degrees to radians. Then your function simply becomes:

from math import sin, cos, radians, pi
def point_pos(x0, y0, d, theta):
    theta_rad = pi/2 - radians(theta)
    return x0 + d*cos(theta_rad), y0 + d*sin(theta_rad)

(as you can see you mixed up sine and cosine in your original function)

(also note the linear angle transformation because angles on compass are clockwise and mathematical angles are counter-clockwise. Also there is an offset between the respective zeroes)

You can also use complex numbers to represent points, which is somewhat nicer than a tuple of coordinates (although a dedicated Point class would be even more appropriate):

import cmath
def point_pos(p, d, theta):
    return p + cmath.rect(d, pi/2-radians(theta))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top