首页 > 解决方案 > 艾伦·唐尼 (Allen Downey) 的《Think Python》一书的 Ex-4.1 第 2 部分

问题描述

下面给出的代码是作者在 Github 上提供的,用于展示如何绘制广义弧,但我不明白的是,在最终的弧函数中,如何通过在开始前稍微左转来减少错误

import math
import turtle


def square(t, length):
    """Draws a square with sides of the given length.

    Returns the Turtle to the starting position and location.
    """
    for i in range(4):
        t.fd(length)
        t.lt(90)


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 i in range(n):
        t.fd(length)
        t.lt(angle)


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) + 3
    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)

标签: pythonpython-3.x

解决方案


# 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)

我认为这是您所指的部分。这似乎是一个多余的步骤,因为它所做的只是在调用折线函数之前向左转,然后在调用折线函数后向右转等量。

这个看似很小的变化所做的是将“折线”从切线更改为相同长度的割线。如果你在一张纸上画出这两种情况,你会发现割线是圆的近似值,因为它与圆有 2 个公共点,而切线只有一个公共点。


推荐阅读