试图找出如何用随机数找到乌龟的最终距离

问题描述

这是我的代码,我试图弄清楚如何获得海龟已经游过的整个长度的总距离,而且我不知道如何才能将其从循环中取出来。不会这样做,因为numsteps是输入。这是去学校的

for a in range(numsteps):
    s = randint(-100,100)
    angle = random() * 2 * pi
    x = s * cos(angle)
    y = s * sin(angle)
    walking.goto(x,y)
distance = sqrt(x ** 2 + y ** 2)
finald.goto(x,y)
print("The final distance is {:,.0f}".format(distance))
print("Your total distance traveled is {}")

解决方法

您必须保存您的上一个位置,以计算从当前位置到它的距离。

然后每次计算距离(在循环的末尾附近)后,当前位置都会变为前一个位置:

from math import sin,cos,pi,sqrt
from random import random,randint

start_x,start_y = 0,0                      # The starting point coordinates
previous_x,previous_y = start_x,start_y   

total_distance = 0                           # We will progressively increase it

numsteps = int(input("Number of steps: "))

for __ in range(numsteps):
    s = randint(-100,100)
    angle = random() * 2 * pi
    x = s * cos(angle)
    y = s * sin(angle)
    # walking.goto(x,y)                     # I commented it out for testing
    distance = sqrt((x - previous_x) ** 2 + (y - previous_y) ** 2)
    total_distance += distance
    prev_x,prev_y = x,y
    
final_distance = sqrt((x - start_x) ** 2 + (y - start_y) ** 2)

print("The final distance is {:,.0f}".format(final_distance))
print("Your total distance traveled is {:,.0f}".format(total_distance))

请注意,__而不是您的a(或其他常规名称)—这个特殊名称(一个或两个下划线字符)表示其值出于我们的兴趣。em>

(因为我们仅将range(numsteps)用作计数器。)

,

我会根据一些观察结果进行简化:

  1. 海龟已经知道距离函数,无需重新发明

  2. 当我们可以朝任何方向前进时,
  3. 向后移动 (负距离)是多余的-实际上与向任何方向前进 没什么不同。>

  4. 我们比计算我们要移动多远,可以更容易地计算我们移动的距离。

这导致代码更像:

from math import pi
from random import random
from turtle import Screen,Turtle

numsteps = int(input("Number of steps: "))

screen = Screen()

walking = Turtle()
walking.radians()

total_distance = 0  # sum of all distances traveled

for _ in range(numsteps):
    previous = walking.position()

    angle = random() * 2 * pi
    distance = random() * 100

    walking.setheading(angle)
    walking.forward(distance)

    total_distance += walking.distance(previous)

final_distance = walking.distance(0,0)  # distance from where we started

print("Your final distance traveled is {:,.0f} pixels".format(final_distance))
print("Your total distance traveled is {:,.0f} pixels".format(total_distance))

screen.exitonclick()

输出

> python3 test.py
Number of steps: 100
Your final distance traveled is 356 pixels
Your total distance traveled is 4,630 pixels
>