使用Python Turtle Module绘制椭圆的意外结果

时间:2017-07-26 03:47:26

标签: python drawing turtle-graphics

我正在尝试使用Python中的Turtle模块绘制椭圆,我的计划如下:

  1. 让起点成为椭圆的焦点
  2. 将初始theta值设置为0
  3. 让乌龟前进,让转发的距离为*(1-e e)/(1-e math.cos(theta))
  4. 让它转身回到原点
  5. 转一圈,更新theta值
  6. 重复上述过程
  7. 这是我的实际代码:

    import turtle
    import math
    wn = turtle.getscreen()
    wn.bgcolor("red")
    My_Turtle = turtle.Turtle()
    My_Turtle.penup()
    My_Turtle.speed(9)
    i=0
    j=0
    a=200
    e=0.5
    x_0 = 20
    theta = 0
    while(i<5000):
        #Plotting squares
        My_Turtle.penup()
        ellipse = a*(1-e*e)/(1-e*math.cos(theta))
        My_Turtle.forward(ellipse)
        My_Turtle.pendown()
        My_Turtle.forward(1)
    
        My_Turtle.left(180)
        My_Turtle.penup()
        My_Turtle.forward(ellipse+1)
    

    然而,结果真的是这样的:(不是完整的图像,但可以看到它已经关闭)

    enter image description here

    任何人都可以向我解释我弄错了吗?非常感谢你!

1 个答案:

答案 0 :(得分:1)

我习惯从中心画一个椭圆,而不是从一个焦点画一个椭圆,所以我读了椭圆数学来了解这个问题。您的关键公式似乎是正确的:

ellipse = a*(1-e*e)/(1-e*math.cos(theta))

问题在于如何进行绘图。首先,您需要添加setheading()以便将乌龟指向正确的方向。 (请记住,默认情况下它是以度为单位的,因此我们需要转换或更改龟的默认值)。其次,如何在绘图中的步骤之间架起桥梁是不够的。

我已经重新编写了下面的代码,并将其与基于中心的解决方案进行了比较,以确认它生成相同的椭圆:

import math
from turtle import Turtle, Screen

my_screen = Screen()

my_turtle = Turtle(visible=False)
my_turtle.speed('fastest')
my_turtle.radians()
my_turtle.penup()

e = 0.5  # linear eccentricity
a = 200  # semi major axis
c = e * a  # distance from center to focal point

my_turtle.goto(-c, 0)  # starting at a focal point
there = (2 * c, 0)  # initialize previous point visited

step = 0.1

theta = step  # already at starting point, so calculate next point

while theta < math.pi * 2 + step:  # overshoot to close curve

    # draw ellipse from one focus point
    my_turtle.setheading(theta)

    distance = a * (1 - e * e) / (1 - e * math.cos(theta))

    my_turtle.forward(distance)
    here = my_turtle.position()
    my_turtle.pendown()
    my_turtle.goto(there)  # draw line from last position to this one
    my_turtle.penup()  # comment out to demonstrate algorithm
    my_turtle.goto(-c, 0)  # return to focal point
    there = here

    theta += step

my_screen.exitonclick()

<强>输出

enter image description here

我把笔留下来用于这种幻觉,所以很明显它是从一个焦点形成椭圆。