使用三角函数计算矩形的新中心

时间:2014-11-09 04:28:48

标签: python python-3.x trigonometry

我目前无法完成作业,而且我一直在努力查明错误数小时。

我有一个圆圈和一个矩形(均由用户点击绘制)。如下所示:

i.stack.imgur(dot)com / 4aXIw.png

使用矩形的中心点,我想计算一个位于圆上的新中心点(对于矩形)。我通过计算角度(θ)并使用三角函数来获得新的中心点来实现这一点。

i.stack.imgur(dot)com / NoCBS.png

但是,当我运行程序时,我得不到正确的结果。如图所示:

i.stack.imgur(dot)com / ZG9Ld.png

我已经检查了一百次,而且我似乎无法确定我搞砸了哪里。我检查了θ,结果度是正确的。这是相关的代码,我怀疑我犯了一个错误:

theta = math.atan((initialrec_y-click1.y)/(initialrec_x-click1.x))
theta = int(math.degrees(theta))

rec_x = click1.x + radius*math.cos(theta)
rec_y = click1.y + radius*math.sin(theta)

如果你想运行它,这是完整的代码:

from graphics import *
import math

def main():

#setup window
win = GraphWin("Traveling Rectangle",600,450)
win.setCoords(0,0,600,450)

click1 = win.getMouse()
click2 = win.getMouse()
radius = click2.x - click1.x
circle = Circle(click1, radius)
circle.draw(win)

click3 = win.getMouse()
click4 = win.getMouse()
rect = Rectangle(click3, click4)
rect.draw(win)
rect.setFill("red")
rect.setOutline("red")

#the centerpoint of the initial rectangle
initialrec_x = (click3.x + click4.x) / 2
initialrec_y = (click3.y + click4.y) / 2

#the trig to calculate the point on the circle
theta = math.atan((initialrec_y-click1.y)/(initialrec_x-click1.x))
theta = int(math.degrees(theta))

#the new centerpoint values of x and y
rec_x = click1.x + radius*math.cos(theta)
rec_y = click1.y + radius*math.sin(theta)

main()

非常感谢帮助!

我道歉,该网站没有让我发布图片。图形库可以在这里找到:mcsp.wartburg(dot)edu / zelle / python / graphics.py

1 个答案:

答案 0 :(得分:0)

我使用的是不同的图形包,但以下内容适用于我:

...
initialrec_y = (click3.y + click4.y) / 2

theta = math.atan2(initialrec_y - click1.y, initialrec_x - click1.x)
rec_x = click1.x + radius * math.cos(theta)
rec_y = click1.y + radius * math.sin(theta)

这会使用atan2函数,该函数会记录yx输入上的符号,以正确计算该点所在的象限并相应地返回一个角度。除此之外,与您的代码的唯一区别在于没有从弧度(atan2返回)到度数的转换。 sincos想要弧度。

相关问题