蟒蛇的海龟和正弦

时间:2015-04-06 00:04:11

标签: python trigonometry turtle-graphics

我试图在python中使用海龟绘制正弦波,但是我遇到了问题,我使用带有goto语句的while循环来绘制波形但是y值在goto是常数(虽然它们确实发生了变化,但只是不在goto中)为什么会这样?因为x表现良好

import math
import turtle

wn = turtle.Screen()f
wn.bgcolor('lightblue')

fred = turtle.Turtle()

x = 0

while x < 360:
    y = math.sin(math.radians(x))
    print y
    fred.goto(x, y)
    x += 1

wn.exitonclick()

2 个答案:

答案 0 :(得分:0)

您的y正在发生变化,但更改太小,无法正确显示在图表中。如果你去goto(x,y*100),这将更加明显:

import math
import turtle

wn = turtle.Screen()
wn.bgcolor('lightblue')

fred = turtle.Turtle()

x = 0

while x < 360:
    y = math.sin(math.radians(x))
    print y*100
    fred.goto(x, y*100)
    x += 1

wn.exitonclick()

答案 1 :(得分:0)

我建议您不要弯曲数据以适合您的图形环境,而是弯曲图形环境以适合您的数据。在Python turtle中,我们可以使用setworldcoordinates()来做到这一点:

from math import pi, sin as sine
from turtle import Screen, Turtle, Vec2D

wn = Screen()
wn.bgcolor('lightblue')
wn.setworldcoordinates(-pi, -2, 3 * pi, 2))

fred = Turtle()

x = 0

while x < 2 * pi:
    position = Vec2D(x, sine(x))
    fred.setheading(fred.towards(position))  # visual detail, arrow follows line
    fred.goto(position)
    x += 0.1

wn.exitonclick()

enter image description here