[英]Turtle graphics in Python 2.7: Drawing an arc
在Python for Software Design第4.12節(第4章)的練習4.1(c)中,聲明了以下版本的函數arc()
:
def arc(t, r, angle):
"""Draws an arc with the given radius and angle.
t: Turtle
r: radius
angle: angle subtended by the arc, in degrees
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 1
step_length = arc_length / n
step_angle = float(angle) / n
# making a slight left turn before starting reduces
# the error caused by the linear approximation of the arc
lt(t, step_angle/2)
polyline(t, n, step_length, step_angle)
rt(t, step_angle/2)
比第4.7節中的原始版本“更好”:
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
(您可以在此處查找子程序的代碼,例如polyline()
)。
我試圖了解為什么以前的版本更好,尤其是按哪個指標。 我們如何定義逼近的真實圓? 有任何想法嗎?
在嘗試繪制草圖之前,我也無法向自己解釋。 如果可以想象,半步角轉彎有助於大致將弧長平分。 通過介於兩者之間,可以對創建的其他區域進行加法和減法,這是一種粗略的校正。
讓我們進行比較。 我們將使用turtle.circle()
作為任意標准,然后使用兩個arc()
例程繪制360度弧(aka圓),半徑比我們的標准小3個像素,半徑比我們大3個像素:
import math
from turtle import Turtle, Screen
def polyline(t, n, length, angle):
"""Draws n line segments.
t: Turtle object
n: number of line segments
length: length of each segment
angle: degrees between segments
"""
for _ in range(n):
t.fd(length)
t.lt(angle)
def arc2(t, r, angle):
"""Draws an arc with the given radius and angle.
t: Turtle
r: radius
angle: angle subtended by the arc, in degrees
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 1
step_length = arc_length / n
step_angle = float(angle) / n
# making a slight left turn before starting reduces
# the error caused by the linear approximation of the arc
t.lt(step_angle/2)
polyline(t, n, step_length, step_angle)
t.rt(step_angle/2)
def arc1(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
screen = Screen()
screen.setup(500, 500)
screen. setworldcoordinates(-250, -50, 250, 450)
thing0 = Turtle()
thing0.circle(200, steps=60)
thing1 = Turtle()
thing1.color("red")
thing1.penup()
thing1.goto(0, 3)
thing1.pendown()
arc1(thing1, 197, 360)
thing2 = Turtle()
thing2.color("green")
thing2.penup()
thing2.goto(0, -3)
thing2.pendown()
arc2(thing2, 203, 360)
screen.exitonclick()
完整的圈子
細節#1
細節#2
我要說的是,第4.12弧(綠色)看起來比第4.7弧(紅色)更好,因為綠色弧線的鋸齒少,並且與我們的標准圓保持一致的3個像素,而紅色弧線則越來越近。 您認為什么標准重要?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.