pythontkintercoordinatestrigonometrycartesian-coordinates

Python coordinate rotations becoming smaller with iterations


I am having an issue with my coordinates becoming infinitesimally smaller as my program iterates through the coordinate rotation algorithm. I have put a gif below that showcases this in a slower framerate; as it continues the line eventually disappears.

https://i.gyazo.com/368fbc65dbc5d3deaa282a4b72ec5d22.mp4

I think the issue is with the sin and cos possibly truncating numbers but I am not sure

def run(root, canvas, line, x, y, width, height):
    # counter clockwise rotation of cartesian coordinates
    # X =  xcosθ + ysinθ
    # Y = -xsinθ + ycosθ

    theta = 1/8

    x, y = tk_to_cart(width/2, height/2, x, y)

    x =  x * cos(theta) + y * sin(theta)
    y = -x * sin(theta) + y * cos(theta)

    x, y = cart_to_tk(width/2, height/2, x, y)

    canvas.delete(line)
    line = canvas.create_line(width/2, height/2, x, y)

    root.after(20, lambda: run(root, canvas, line, x, y, width, height))

tk_to_cart and cart_to_tk are just simple translations across the canvas because of tkinter's coordinate system having 0,0 in the top left.


Solution

  • Probably loss of precision somewhere along the line, particularly if tk_to_cart and/or cart_to_tk round or truncate to integer.

    A couple of ideas:

    Something like:

    def run(root, canvas, line, x_cart, y_cart, width, height, theta=0):
        # counter clockwise rotation of cartesian coordinates
        # X =  xcosθ + ysinθ
        # Y = -xsinθ + ycosθ
    
        theta += 1/8
    
        x_rot =  x_cart * cos(theta) + y_cart * sin(theta)
        y_rot = -x_cart * sin(theta) + y_cart * cos(theta)
    
        x_tk, y_tl = cart_to_tk(width/2, height/2, x_rot, y_rot)
    
        canvas.delete(line)
        line = canvas.create_line(width/2, height/2, x_tk, y_tk)
    
        root.after(20, lambda: run(root, canvas, line, x_cart, y_cart, width, height, theta))