math.tan in python outputting strange values

import turtle
from tkinter import *
import math

root = Tk()

screen = turtle.Screen()

t = turtle.Turtle()
t.penup()
t.speed('fastest')

w = turtle.Turtle()
w.penup()
w.speed('fastest')
w.goto(100, 0)
w.left(90)
w.pendown()
w.forward(300)
w.back(600)
w.penup()
w.hideturtle()


def x_value(data):
    global angle
    angle = float(data)
    print(f"Angle: {angle}")
    t.setheading(angle)

x = Scale(root, from_=90, to=-90, command=x_value)
x.pack()


def intercept_finder():
    x_difference = 100-int(t.xcor())
    print(x_difference)


    #t.forward(100*math.tan(angle))
    tan_section = math.tan((angle))
    print(f"Tan_Section: {tan_section}")
    print(f"Tan: {100*tan_section}")
    print(f"X_Cord = {t.xcor()}")
    print(f"Y_Cord = {t.ycor()}")

get_x = Button(root, text='Enter', bg='red', width=5, command=intercept_finder)
get_x.pack()

screen.mainloop()

When angle is 50, the expected math.tan is supposed to be 119.1753593. math.tan gives me -0.27190061199763077.

I’m trying to make it so turtle finds the y cordinates it will be 100 steps more than its origina x value, so its starting cords (0,0) and the ending cord (100, ??). To find the y coordinates i need to use the formula b x tan(a), where b is the 100 steps and a is the angle.

I’m using:
b = 100
a = 50

Use these values for testing if the program outputted the correct output.

>Solution :

The math.tan() function in Python expects its input to be in radians, not degrees. You need to convert the angle from degrees to radians before passing it to the math.tan() function.

import turtle
from tkinter import *
import math

root = Tk()

screen = turtle.Screen()

t = turtle.Turtle()
t.penup()
t.speed('fastest')

w = turtle.Turtle()
w.penup()
w.speed('fastest')
w.goto(100, 0)
w.left(90)
w.pendown()
w.forward(300)
w.back(600)
w.penup()
w.hideturtle()


def x_value(data):
    global angle
    angle = float(data)
    print(f"Angle: {angle}")
    t.setheading(angle)

x = Scale(root, from_=90, to=-90, command=x_value)
x.pack()


def intercept_finder():
    x_difference = 100-int(t.xcor())
    print(x_difference)


    #t.forward(100*math.tan(angle))
    tan_section = math.tan(math.radians(angle))  # Convert degrees to radians
    print(f"Tan_Section: {tan_section}")
    print(f"Tan: {100*tan_section}")
    print(f"X_Cord = {t.xcor()}")
    print(f"Y_Cord = {t.ycor() + 100*tan_section}")  # Add the y coordinate

get_x = Button(root, text='Enter', bg='red', width=5, command=intercept_finder)
get_x.pack()

screen.mainloop()

Now with the angle 50: the output would be what you expected

Angle: 50.0
Tan_Section: 1.1917535925942099
Tan: 119.17535925942098
X_Cord = 0.0
Y_Cord = 119.17535925942098

Leave a Reply