簡體   English   中英

python用弧度找到x,y坐標,給定角度

[英]python find x,y coordinates with radian, angle given

如果圓的弧度和角度以 (0,0) 為圓心,我試圖找到多個 (x,y) 坐標。 比方說,弧度 = 4,角度 = 360/n

我需要多個坐標,這意味着如果我的 n = 4 那么我的角度就是 90 度。 所以我不僅需要 90 度的 x,y 坐標,還需要 90,180,270,360 度的坐標。

同樣,如果我的 n= 6,那么我需要 360/6=60 處的 x,y 坐標。 所以每+60度直到360度。 示例 x,y 坐標為 60、120、180、240、300、360。

我只知道如何為一位天使做到這一點,這就是我所嘗試的

import math

number = 4
Angles_req = (360/number)
radius = 4

x = round(4*math.cos(360/number), 2)
y = round(4*math.sin(360/number), 2)

任何幫助,將不勝感激。 謝謝!

我將在沒有numpy 的情況下執行此操作,盡管它會更容易

import math

def circle_sections(divisions, radius=1):
    # the difference between angles in radians -- don't bother with degrees
    angle = 2 * math.pi / divisions

    # a list of all angles using a list comprehension
    angles = [i*angle for i in range(divisions)]

    # finally return the coordinates on the circle as a list of 2-tuples
    return [(radius*math.cos(a), radius*math.sin(a)) for a in angles]

輸出

circle_sections(4)

#[(1.0, 0.0),
# (6.123233995736766e-17, 1.0),
# (-1.0, 1.2246467991473532e-16),
# (-1.8369701987210297e-16, -1.0)]

circle_sections(6)

#[(1.0, 0.0),
# (0.5000000000000001, 0.8660254037844386),
# (-0.4999999999999998, 0.8660254037844387),
# (-1.0, 1.2246467991473532e-16),
# (-0.5000000000000004, -0.8660254037844384),
# (0.4999999999999993, -0.866025403784439)]

我沒有在此舍入這些,因為通常這只是您為格式化所做的事情,但如果您確實想要,只需

return [(round(radius*math.cos(a), 2), round(radius*math.sin(a), 2)) for a in angles]

這是你如何在 numpy 中做到這一點:

import numpy as np 
import math

radius = 4
number = 4
rad = np.radians(np.linspace(360/number,360,number))
xy = radius *np.array([[math.cos(x),math.sin(x)] for x in rad])

您應該能夠使用循環遍歷 [1, n]。

例如:

import math

n = 4
r = 4

for i in range(1, n + 1):
    theta = math.radians((360 / n) * i)
    x = round(r * math.cos(theta), 2)
    y = round(r * math.sin(theta), 2)

您可以遍歷所有子角度,然后生成 x,y 對的元組。

def divide_angle(num_units, angle=360):
    for unit in range(num_unit):
        sub_angle = (unit+1)*angle//unit
        x = round(4*math.cos(sub_angle), 2)
        y = round(4*math.sin(sub_angle), 2)
        yield x,y

我對你的問題的幾分錢:

n = 6
step = int(360/n)
for i in range(step, 361, step):
    angle = math.radians(i)
    x = round(4*math.cos(angle), 2)
    y = round(4*math.sin(angle), 2)
    # Do something with x and y

您可以嘗試打印angle以說服自己它提供您想要的。

要獲得 360° 中的所有部分,您可以使用range(0, 360, 360//n)的列表理解。 此外,您可以使用cmath來獲取極坐標中的復數,而不是使用sincos

>>> radius, n = 4, 3

>>> [cmath.rect(radius, math.radians(a)) for a in range(0, 360, 360//n)]
[(4+0j),
 (-1.9999999999999991+3.464101615137755j),
 (-2.0000000000000018-3.4641016151377535j)]

這對於對這些點進行進一步計算也可能很有用,例如添加它們。 如果您更喜歡(圓形)元組,則可以使用嵌套列表理解:

>>> [(round(c.real, 2), round(c.imag, 2))
...  for c in (cmath.rect(radius, math.radians(a)) for a in range(0, 360, 360//n))]
[(4.0, 0.0), (-2.0, 3.46), (-2.0, -3.46)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM