python - 理解 "Think Python"中的 turtle 圆和弧

标签 python geometry turtle-graphics

在“Think Python”的界面设计部分中,我需要帮助理解圆和圆弧函数的方法,如下所示:

import turtle
import polygon
bob = turtle.Turtle()

print(bob)

def polygon(t, n, length):

    angle = 360 / n
    for i in range(n):
        t.fd(length)
        t.lt(angle)

然后,本书介绍了另一种使用多边形函数绘制圆的方法:

def circle(t, r):

    circumference = 2 * math.pi * r
    n = int(circumference / 3 ) + 1
    length = circumference / n
    polygon(t, n, length)

我不明白的地方:

  • 我不知道他们为什么定义circumference来绘制圆以及它是如何绘制圆的。

  • 如果我调用像circle(bob, 100)这样的函数,那么它只会绘制圆的一小部分而不是整个圆。

  • 我不明白为什么需要 n,以及该过程如何形成一个圆。

最佳答案

I have no idea why they define circumference to draw circle and how it take a work to draw a circle

我们可视化圆的一种方法是绘制一个多边形,其边数等于圆的(整数)周长,每条边的长度为 1。对于半径 = 100 的圆,则为:

polygon(bob, 628, 1)  # 628 = 2 * PI * 100

绘制了一个漂亮但缓慢的圆圈:

enter image description here

我们可以通过使用更粗略的近似来加快速度。上面的circle()函数将多边形的边数任意除以3,然后将每条边的长度增加3:

polygon(bob, 209, 3)

这只是一个稍微粗糙的圆圈,但绘制速度更快:

enter image description here

If I call the function like circle(bob, 100) then it only draws a fraction of circle not the whole circle.

我相信您将上面定义的circle()函数与turtle附带的circle()方法混淆了。作者以这种方式重复使用“圈子”名称,令人困惑。 turtle circle() 方法的第二个参数是一个范围:

extent - an angle - determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position.

所以“Think Python”函数调用:

circle(bob, 100)

画一个半径为100的圆:

enter image description here

turtle 方法:

bob.circle(100, 90)

根据半径 100 绘制圆弧(1/4 圆):

enter image description here

I don't understand why n is needed, and how that procedure can make a circle.

n 是近似圆的多边形的边数:

n = int(circumference / 3 ) + 1
length = circumference / n
polygon(t, n, length)

从半径 100 开始,如果我们将上面的“3”替换为 1,我们将得到一个具有更多 (629) 条边的多边形:

n = int(circumference / 1) + 1  # n = 629
length = circumference / n  # length = 0.9989

或者大致:

polygon(t, 628, 1)

如上图所示。但如果我们用“27”替换“3”,我们会得到一个由 24 条边的多边形近似的圆:

n = int(circumference / 27 ) + 1  # n = 24
length = circumference / n  # length = 26.1799

enter image description here

原来的“3”值应该是一个附加参数 - 在 turtle.circle() 方法中,它大致相当于 steps 参数:

As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. May be used to draw regular polygons.

bob.circle(100, steps=12)

enter image description here

关于python - 理解 "Think Python"中的 turtle 圆和弧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998050/

相关文章:

python - turtle 模块错误

python - sage中调用函数出错

c# - 如何找到给定纬度/经度以北 x 公里的纬度/经度?

javascript - 用圆形区域填充二维数组

css - 完美重叠的圆形 div

python - 除了冲压之外,如何在Python turtle graphics 中绘制椭圆?

python - 如何高效地将 Matlab 引擎数组转换为 numpy ndarray?

python - wxPython - 创建一个在我的 TextCtrl 面板中生成位图图像的按钮

python - 如何删除 2D 矩阵中值为 0 的前 n 列/行?

python - 有没有办法镜像Python函数?