python turtle如何画椭圆

2025-11-25 21:04:09

1、如果手头有笔有纸的话,可以拿出来一起推导一边,纪念我们曾经的数学。

让我们先画了一个椭圆,标号坐标系。长轴为a短轴为b。方程应该都没忘吧。

x2/a2 + y2/b2 = 1.

它的参数方程为x = acosθ ,y = bsinθ。

由于我喜欢从(0,-b)点开始,参数方程改用x=asinθ,y=-bcosθ。

python turtle如何画椭圆

2、我们当然也可以用微积分的想法,转一个固定角,算出走多少距离,但这个误差太大了,消耗代价也大。

用此法我们可以很容易算出nextPoint = [a*math.sin((i+1)*minAngle),-b*math.cos((i+1)*minAngle)]

遍历后的成果图如下:

python turtle如何画椭圆

3、来看以下函数:

def ellipse(a,b,angle,steps):

    minAngle = (2*math.pi/360) * angle / steps

    turtle.penup()

    turtle.setpos(0,-b)

    turtle.pendown()

    for i in range(steps):

        nextPoint = [a*math.sin((i+1)*minAngle),-b*math.cos((i+1)*minAngle)]

        turtle.setpos(nextPoint)

ellipse(a,b,angle,steps):a,b是长轴和短轴,angle是转过多少角度,steps是行进距离。

python turtle如何画椭圆

4、这里用的penup和pendown是为了防止从其他位置到原点画圆时哗啦带一条直线过来,当然,如果你不想在圆点画圆,你只需要用(x,y)加到上述函数,就能指定从哪个点开始画圆。

python turtle如何画椭圆

5、画一个水平的椭圆还是应用不广,我们尝试着如何画有倾角的椭圆。试想想,一个水平的椭圆进行旋转是不是就得到了一个有倾角的椭圆,等价对椭圆上所有的点进行旋转,而旋转则有明确的旋转矩阵,效果如下图:

python turtle如何画椭圆

6、def ellipseR(a,b,angle,steps,rotateAngle):

    minAngle = (2*math.pi/360) * angle / steps

    rotateAngle = rotateAngle/360*2*math.pi

    turtle.penup()

    turtle.setpos(b*math.sin(rotateAngle),-b*math.cos(rotateAngle))

    turtle.pendown()

    for i in range(steps):

        nextPoint = [a*math.sin((i+1)*minAngle),-b*math.cos((i+1)*minAngle)]

        nextPoint = [nextPoint[0]*math.cos(rotateAngle)-nextPoint[1]*math.sin(rotateAngle),

                     nextPoint[0]*math.sin(rotateAngle)+nextPoint[1]*math.cos(rotateAngle)]

        turtle.setpos(nextPoint)

rotateAngle为你要旋转的角度,为360度。

python turtle如何画椭圆

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢