在 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()
, here 等子程序代码可以自己查)
我试图了解为什么以前的版本更好,特别是在哪个指标上。我们如何定义我们正在近似的真实圆?有什么想法吗?
最佳答案
让我们来个烘烤比较。我们将使用 turtle.circle()
作为任意标准,然后使用两个 arc()
例程绘制 360 度圆弧(又名圆),一个小 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 个像素,而红色弧线则越来越近.您认为哪些标准很重要?
关于python - Python 2.7 中的 turtle 图形 : Drawing an arc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375000/