Python:使用数学和海龟库绘制切线图

Python: draw tangent graph using math & turtle libraries

我在这个任务上卡了好几天。虽然,解决方案应该很简单。我应用数学和海龟库来绘制 3 个图形:正弦、余弦和正切,振幅为 200。问题是我无法构建应绘制的正切图。 这是我应该做的:

这是我得到的:

如你所见,我的乌龟上去了就再也没有回来。 请不要建议我使用 numpy。这不在我的任务范围之内。 感谢您的提前!

import math
import turtle

ws = turtle.Screen()
ws.bgcolor("white")
t = turtle.Turtle()
for i in [(0,250), (0,0), (0,-250), (0,0), (400,0), (0,0)]:
    t.goto(i, None)
    t.write(i, font=("Arial", 12))

t.color("red")

for angle in range(360):
    y = math.sin(math.radians(angle))        
    t.goto(angle, y * 200)

t.penup()
t.setpos(0,200)
t.goto(0,200)
t.pendown()
t.color("blue")

for angle in range(360):
    y = math.cos(math.radians(angle))       
    t.goto(angle, y * 200)

t.penup()
t.setpos(0,0)
t.goto(0,0)
t.pendown()
t.color("green")

for angle in range(360):
    y = math.tan(math.radians(angle))
    t.goto(angle, y * 200)

ws.exitonclick()

为了证明它应该有效,下面是我使用海龟图形绘制正弦、余弦和切线的极简实现:

import math
from turtle import Turtle, Screen

RESOLUTION = 0.1

def plot(x_points, y_points):
    for i, y in enumerate(y_points):
        if abs(y) <= 2.0:
            yertle.goto(x_points[i], y)
            yertle.pendown()
        else:
            yertle.penup()

    yertle.penup()

screen = Screen()
screen.setworldcoordinates(0, -1.5, 2 * math.pi / RESOLUTION, 1.5)

yertle = Turtle()
yertle.penup()

x = range(int(2 * math.pi / RESOLUTION))

yertle.color("blue")
plot(x, (math.cos(n * RESOLUTION) for n in x))

yertle.color("red")
plot(x, (math.sin(n * RESOLUTION) for n in x))

yertle.color("dark green")
plot(x, (math.tan(n * RESOLUTION) for n in x))

screen.exitonclick()

输出

我的猜测是您等待切线绘制的时间不够长,即它正在慢慢地从 window 上绘制很多点并最终会重新出现在屏幕上。我的代码解决了这个问题。

试试这个。临近我的工作,没有时间变得更好:

对于范围内的角度(360): y=0

y = math.tan(math.radians(angle))
if y<1 and y>-1:
    t.goto(angle, y * 200)

与asipmtotas

for angle in range(360):
    t.penup()
    y = math.tan(math.radians(angle))

    if y<1 and y>-1:
        t.pendown()
        t.goto(angle, y * 200)
    else:
        t.penup()
        #t.pendown()
        t.goto(angle, 200)