Python Forum

Full Version: Python Turtle. Pointers of the "arrow" direction of the vector.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Please tell me how to position the arrows in the direction of the vector?


[Image: 244280916_5472eec8d5877641013c65d69a0549a8_800.png]

from math import sin, cos, tan, atan, degrees, pi
from random import randint


import turtle


R = 100 # the radius of the circles
r = 25 # the radius of the elements circles
n = 4 # the number of rows of the matrix
Fi = 2*pi/n # the angle of displacement in radians [1.5707963267948966]
p = [] # the coordinates of the circles on the x & y axis
matrix = [[randint(0,9) for _ in range(n)] for _ in range(n)] # generating a random two-dimensional matrix


win = turtle
win.setup(400,400)
win.title("Dependence of matrix elements")

for i in range(n):
    """Calculating the coordinates of the location of circles."""
    p += [[(R * cos(Fi * i)), (R * sin(Fi * i))]] 


for i in range(n):
    """Drawing circles and numbering them."""
    win.speed(10)
    win.teleport(p[i % n][0], p[i % n][1] - r)
    win.circle(r)
    win.teleport(p[i % n][0], p[i % n][1])
    win.dot(5)
    win.teleport(p[i % n][0], p[i % n][1] + r)
    win.write(i+1)


win.speed(1)
for i in range(n):
    for j in range(n):
        if matrix[i][0] != 0 and matrix[i][j] != 0 and i != j:
            """Finding dependencies of matrix elements"""
            angle = tan((p[i][1] - p[j][1]) / (p[i][0] - p[j][0])) # calculation of the slope angle tangent
            angle = atan(angle) # calculation of the catangence
            angle = degrees(angle) # conversion from meridians to degrees
        
            win.teleport(p[i][0], p[i][1]) # setting the turtle to the beginning of the vector
            win.goto(p[j][0], p[j][1]) # draw a vector

            
            win.setheading(angle + 180) # turn the arrow according to the angle of the vector
            win.stamp() #  print an arrow on the canvas


win.done()
You need to use atan2(y, x) instead of atan(). The sign of x and y are needed to derive the correct quadrant.

You can draw fewer lines if you draw the arrows at both ends of the lines.
from math import sin, cos, degrees, pi, atan2
import turtle
 
 
R = 100
r = 25
n = 4
Fi = 2*pi/n
win = turtle
win.setup(400, 400)
win.title("Dependence of matrix elements")

win.speed(10)
p = []
for i in range(4):
    x = R * cos(Fi * i)
    y = R * sin(Fi * i)
    p.append((x, y))
    win.teleport(x, y - r)
    win.circle(r)
    win.teleport(x, y)
    win.dot(5)
    win.teleport(x + 4, y + r)
    win.write(i + 1)
 
 
win.speed(1)
j = 3
for i in (0, 1, 2, 3, 1, 2, 0):
    win.teleport(p[j][0], p[j][1])
    angle = atan2(p[j][1] - p[i][1], p[j][0] - p[i][0])
    angle = degrees(angle)
    win.setheading(angle)
    win.stamp()
    win.setheading(angle + 180)
    win.goto(p[i][0], p[i][1])
    win.stamp()
    j = i

win.done()