使用Python Turtle模块绘制椭圆时出现意外结果
我正在尝试使用Python中的Turtle模块绘制一个椭圆,我的计划如下: 让起点成为椭圆的焦点 将初始θ值设置为0 让乌龟前进,让前进的距离为*1-ee/1-emath.costheta 让它转身回到原来的位置 做一个很小的转弯,更新θ值 重复上述过程 这是我的实际代码:使用Python Turtle模块绘制椭圆时出现意外结果,python,drawing,turtle-graphics,Python,Drawing,Turtle Graphics,我正在尝试使用Python中的Turtle模块绘制一个椭圆,我的计划如下: 让起点成为椭圆的焦点 将初始θ值设置为0 让乌龟前进,让前进的距离为*1-ee/1-emath.costheta 让它转身回到原来的位置 做一个很小的转弯,更新θ值 重复上述过程 这是我的实际代码: import turtle import math wn = turtle.getscreen() wn.bgcolor("red") My_Turtle = turtle.Turtle() My_Turtle.penup(
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)
然而,结果是这样的:不是完整的图像,但可以看到它已经关闭
谁能解释一下我哪里弄错了?多谢各位 我习惯于从中心画椭圆,而不是从一个焦点画椭圆,所以我阅读了椭圆数学来了解这一点。您的关键公式似乎是正确的:
ellipse = a*(1-e*e)/(1-e*math.cos(theta))
问题是如何绘制图形。首先,您需要添加设置标题,以便将海龟指向正确的方向。记住,默认情况下,它是以度为单位的,所以我们需要转换或更改海龟的默认值。其次,如何在图形中的步骤之间建立桥梁是不够的
我重新编写了下面的代码,并将其与基于中心的解决方案进行了比较,以确认它生成了相同的椭圆:
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()
输出
我放下笔来做这个幻觉,所以很明显它是从一个焦点形成椭圆的。哎呀,忘了修改第二幅图像的标题,这是我的程序的输出,显然不是椭圆。你应该在问题中发布代码;不是像图像一样。@JeroenHeier,我在问题中添加了他的代码文本,作为解决方案的副作用。@JeroenHeier,谢谢你的建议,这是我第一次来这里,所以我非常熟悉规范。以后一定要这么做!太多了!!最后发现我遇到的是航向问题。