为什么Python Turtle不完全遵循网格?
我偶然发现了这个事实,当时我正在写一个单独的程序时,我很好奇它为什么会发生,以及是否有一种方法可以阻止它发生。
下面的代码是一个简单的程序来说明这一点。乌龟最初似乎遵循网格,即与X或Y轴平行的行进。海龟的印刷坐标的前三个显示了这一点。经过两个方向的变化,如随后的坐标打印输出所示,乌龟似乎从平行到X或Y轴偏向,即使标题应始终是90的倍数。
t = turtle.Turtle()
window = turtle.Screen()
def draw_square():
for i in range(4):
print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
t.forward(100)
t.left(90)
def draw_line():
for i in range(10):
t.forward(20)
print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
draw_square()
draw_line()
I stumbled on this fact while working on a separate program I am writing, and am curious about why it happens and whether there is a way to stop it happening.
The code below is for a simple program to illustrate this. The turtle initially seems to follow a grid i.e. travels parallel to either the x or y-axis. This is shown by the first three of the turtles's printed coordinates. After two changes of direction the turtle seems to veer off from parallel to x or y-axis, as shown in subsequent coordinate printouts, even though the heading should always be a multiple of 90.
t = turtle.Turtle()
window = turtle.Screen()
def draw_square():
for i in range(4):
print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
t.forward(100)
t.left(90)
def draw_line():
for i in range(10):
t.forward(20)
print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
draw_square()
draw_line()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎只是浮点精度错误。
您看到的差异确实很小,您可以忽略它们。
如果您希望看到更清洁的数字,则可以将它们围成几个小数(在此示例中为3),然后再打印它们:
It seems to be just a floating-point precision error.
The differences you are seeing are really tiny, you can ignore them.
If you prefer seeing cleaner numbers, you can just round them to a few decimals (3 in this example) before printing them: