python 将一个点逆时针旋转一个角度
python rotating a point counterclockwise by an angle
我有这种逆时针旋转一个点的方法。
def rotate(self, rad):
self.x = math.cos(rad)*self.x - math.sin(rad)*self.y
self.y = math.sin(rad)*self.x + math.cos(rad)*self.y
但是当我给它传递一个点来旋转时,只有 x 坐标被正确旋转了。例如,我尝试将点 (0,25) 旋转 π/3 。我应该得到 (-22,13) 因为我正在四舍五入答案。相反,我得到 (-22,-6).
这里的问题是您保存 self.x
的新值并使用相同的值作为输入来计算 self.y
试试这个:
def rotate(self, rad):
x = math.cos(rad)*self.x - math.sin(rad)*self.y
self.y = math.sin(rad)*self.x + math.cos(rad)*self.y
self.x = x
是的,您已经更改了第一个等式中的 x。于是
self.x = math.cos(rad)*self.x - math.sin(rad)*self.y
self.x = 0 - 6
所以第二个等式是
self.y = math.sin(rad)*self.x + math.cos(rad)*self.y
self.y = math.sin(math.pi/3)*(-6) + math.cos(math.pi/3)*25
>>> def rotate(x, y, rad):
print x, y, rad
xx = math.cos(rad)*x - math.sin(rad)*y
yy = math.sin(rad)*x + math.cos(rad)*y
print xx, yy
return(xx, yy)
>>> rotate(0, 25, math.pi/3)
0 25 1.0471975512
-21.6506350946 12.5
(-21.650635094610966, 12.500000000000004)
我有这种逆时针旋转一个点的方法。
def rotate(self, rad):
self.x = math.cos(rad)*self.x - math.sin(rad)*self.y
self.y = math.sin(rad)*self.x + math.cos(rad)*self.y
但是当我给它传递一个点来旋转时,只有 x 坐标被正确旋转了。例如,我尝试将点 (0,25) 旋转 π/3 。我应该得到 (-22,13) 因为我正在四舍五入答案。相反,我得到 (-22,-6).
这里的问题是您保存 self.x
的新值并使用相同的值作为输入来计算 self.y
试试这个:
def rotate(self, rad):
x = math.cos(rad)*self.x - math.sin(rad)*self.y
self.y = math.sin(rad)*self.x + math.cos(rad)*self.y
self.x = x
是的,您已经更改了第一个等式中的 x。于是
self.x = math.cos(rad)*self.x - math.sin(rad)*self.y
self.x = 0 - 6
所以第二个等式是
self.y = math.sin(rad)*self.x + math.cos(rad)*self.y
self.y = math.sin(math.pi/3)*(-6) + math.cos(math.pi/3)*25
>>> def rotate(x, y, rad):
print x, y, rad
xx = math.cos(rad)*x - math.sin(rad)*y
yy = math.sin(rad)*x + math.cos(rad)*y
print xx, yy
return(xx, yy)
>>> rotate(0, 25, math.pi/3)
0 25 1.0471975512
-21.6506350946 12.5
(-21.650635094610966, 12.500000000000004)