Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

math - Rotate point about another point in degrees python

If you had a point (in 2d), how could you rotate that point by degrees around the other point (the origin) in python?

You might, for example, tilt the first point around the origin by 10 degrees.

Basically you have one point PointA and origin that it rotates around. The code could look something like this:

PointA=(200,300)
origin=(100,100)

NewPointA=rotate(origin,PointA,10) #The rotate function rotates it by 10 degrees
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following rotate function performs a rotation of the point point by the angle angle (counterclockwise, in radians) around origin, in the Cartesian plane, with the usual axis conventions: x increasing from left to right, y increasing vertically upwards. All points are represented as length-2 tuples of the form (x_coord, y_coord).

import math

def rotate(origin, point, angle):
    """
    Rotate a point counterclockwise by a given angle around a given origin.

    The angle should be given in radians.
    """
    ox, oy = origin
    px, py = point

    qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
    qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
    return qx, qy

If your angle is specified in degrees, you can convert it to radians first using math.radians. For a clockwise rotation, negate the angle.

Example: rotating the point (3, 4) around an origin of (2, 2) counterclockwise by an angle of 10 degrees:

>>> point = (3, 4)
>>> origin = (2, 2)
>>> rotate(origin, point, math.radians(10))
(2.6375113976783475, 4.143263683691346)

Note that there's some obvious repeated calculation in the rotate function: math.cos(angle) and math.sin(angle) are each computed twice, as are px - ox and py - oy. I leave it to you to factor that out if necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...