Python:根据点A的距离和角度找到点B的x,y坐标

3 投票
1 回答
9212 浏览
提问于 2025-04-18 04:09

在Python中有没有现成的函数,可以根据一个点A(x0, y0)和一个给定的角度(以度为单位)来找到另一个点B的X和Y坐标呢?

from math import cos, sin

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

这里的 x0 是点A的X坐标, y0 是点A的Y坐标, dist 是点A到点B的距离, theta 是点B相对于北方(0°)的角度,这个角度是用指南针测量的。

1 个回答

7

你只需要一个函数来把角度转换成弧度。这样你的函数就变得简单了:

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)

(你可以看到你在原来的函数中把正弦和余弦搞混了)

(另外要注意角度的线性转换,因为指南针上的角度是顺时针的,而数学上的角度是逆时针的。还有它们的零点位置是不同的)

你也可以使用复数来表示点,这比用坐标元组要好一些(不过如果有一个专门的Point类会更合适):

import cmath
def point_pos(p, d, theta):
    return p + cmath.rect(d, pi/2-radians(theta))

撰写回答