使用多边形制作给定半径的圆
Using a polygon to make a circle of a given radius
我正在教一些 children 抽象的概念。我目前使用的示例是将正方形、三角形、星形等概括为多边形。
def polygon(l, s, a):
for i in range(s):
forward(l)
left(180 - a)
要制作一个正方形,我会写 polygon(100, 4, 90)
和一个三角形 polygon(100, 3, 60)
。
我知道python乌龟有画圆的功能,但我想用我的多边形功能画圆
现在我的问题是,如何使用多边形构造给定半径的圆?
看来我必须回答我自己的问题了。为了用多边形做一个圆,我想到了这个:
def ccircle(radius, precision=100):
total_internal_angle = 360
angle = total_internal_angle / precision
circumference = 2 * math.pi * radius
polygon(circumference/precision, precision, 180 - angle)
你的回答很好! (+1) 如果我们想更好地模拟 turtle 自己的 circle()
方法,我会做一些调整。第一个是一旦半径达到合理大小时,海龟的圆圈的默认精度为 60 条边。其次,乌龟的圆圈开始的角度略有不同:
from math import pi
from turtle import *
def polygon(length, sides, angle):
for _ in range(sides):
forward(length)
left(180 - angle)
def circle_via_polygon(radius, precision=60):
total_internal_angle = 360
angle = total_internal_angle / precision
circumference = 2 * pi * radius
left(angle / 2) # match turtle's circle() method
polygon(circumference / precision, precision, 180 - angle)
right(angle / 2) # ditto
color('blue')
circle(150) # turtle's own circle()
color('red')
circle_via_polygon(150) # circle() using polygon()
exitonclick()
我正在教一些 children 抽象的概念。我目前使用的示例是将正方形、三角形、星形等概括为多边形。
def polygon(l, s, a):
for i in range(s):
forward(l)
left(180 - a)
要制作一个正方形,我会写 polygon(100, 4, 90)
和一个三角形 polygon(100, 3, 60)
。
我知道python乌龟有画圆的功能,但我想用我的多边形功能画圆
现在我的问题是,如何使用多边形构造给定半径的圆?
看来我必须回答我自己的问题了。为了用多边形做一个圆,我想到了这个:
def ccircle(radius, precision=100):
total_internal_angle = 360
angle = total_internal_angle / precision
circumference = 2 * math.pi * radius
polygon(circumference/precision, precision, 180 - angle)
你的回答很好! (+1) 如果我们想更好地模拟 turtle 自己的 circle()
方法,我会做一些调整。第一个是一旦半径达到合理大小时,海龟的圆圈的默认精度为 60 条边。其次,乌龟的圆圈开始的角度略有不同:
from math import pi
from turtle import *
def polygon(length, sides, angle):
for _ in range(sides):
forward(length)
left(180 - angle)
def circle_via_polygon(radius, precision=60):
total_internal_angle = 360
angle = total_internal_angle / precision
circumference = 2 * pi * radius
left(angle / 2) # match turtle's circle() method
polygon(circumference / precision, precision, 180 - angle)
right(angle / 2) # ditto
color('blue')
circle(150) # turtle's own circle()
color('red')
circle_via_polygon(150) # circle() using polygon()
exitonclick()