Parth Ratra
Parth Ratra

Reputation: 11

Making a triangle using the turtle but the sides don't connect at the end

import numpy as np
import math as m
import turtle as t

s=[3, 4, 5]

#expression below is used to calculate the angle between two sides of a triangle
a1=m.degrees(np.arccos(((s[1]**2 + s[2]**2 - s[0]**2) / (2 * s[1] * s[2]))))
a2=m.degrees(np.arccos(((s[0]**2 + s[2]**2 - s[1]**2) / (2 * s[0] * s[2]))))
a3=m.degrees(np.arccos(((s[0]**2 + s[1]**2 - s[2]**2) / (2 * s[0] * s[1]))))

a=[a1, a2, a3]
print(a)

p=t.Turtle()

for i in range(len(a)):
    p.forward(s[i]*25)
    p.left(180-a[i])

t.done()

the angles calculated are correct and the turtle is running fine too, except it just doesn't connect at the end. i suspect maybe the angles and the sides must be in different orientation to make it work, but i can't find the correct orientation for that.

Upvotes: 0

Views: 62

Answers (2)

cdlane
cdlane

Reputation: 41905

For this to work for arbitrary triangles, your ordering of the angle equations can't be arbitrary, you need to do them in order. Rather than reordering the angles in the list, as @SergeBallesta reasonably does (+1), I would make sure your angle equations are also done in the same order as the sides:

# s0 -> s1 -> s2 -> s0

a1=m.degrees(np.arccos(((s[0]**2 + s[1]**2 - s[2]**2) / (2 * s[0] * s[1]))))
a2=m.degrees(np.arccos(((s[1]**2 + s[2]**2 - s[0]**2) / (2 * s[1] * s[2]))))
a3=m.degrees(np.arccos(((s[2]**2 + s[0]**2 - s[1]**2) / (2 * s[2] * s[0]))))

A complete rework follows below, including switching turtle to radians rather than switching all the angles to degrees:

import turtle
from math import pi
from numpy import arccos

sides = [3, 4, 5]

# Calculate the angles between sides of a triangle
a1 = arccos(((sides[0]**2 + sides[1]**2 - sides[2]**2) / (2 * sides[0] * sides[1])))
a2 = arccos(((sides[1]**2 + sides[2]**2 - sides[0]**2) / (2 * sides[1] * sides[2])))
a3 = arccos(((sides[2]**2 + sides[0]**2 - sides[1]**2) / (2 * sides[2] * sides[0])))

angles = [a1, a2, a3]

turtle.radians()

for side, angle in zip(sides, angles):
    turtle.forward(side * 25)
    turtle.left(pi - angle)

turtle.done()

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149145

Hmm, 3-4-5 is the famous proportion known since ancient Aegypt to build a right triangle. As you use the line sizes in that order, the first angle must be the right angle.

Just change a to:

a = [a3, a1, a2]

and your turtle will give you a nice right triangle.

Upvotes: 1

Related Questions