【问题标题】:Random Path in Circle, Python 2.7圆圈中的随机路径,Python 2.7
【发布时间】:2018-03-25 14:12:02
【问题描述】:
I'm trying to generate a random path from the center of a circle and count how     many steps it takes to exit the circle, my programming language is python 2.7. I've imported random and numpy.

我编写了一些伪代码来帮助我记住我想要完成的任务:

Start at center of circle
Keep track of step count
Step distance=1 step
Radius of Circle=500 steps
While location<500 steps from center:
    take=1 step in random angle direction
    continue while loop
How many steps?

这段代码的每一部分都有问题。我不知道从哪里开始, 我想我必须附加到一个数组,这样我才能知道我什么时候退出了圆圈,但我不知道如何跟踪我的坐标。

更新

这是我目前写的代码,我会在修改时更新:

#Start code
#Import modules
import numpy

#Define constants
r=500
step=1
step_count=0

#Defining origin in circle
x=0
y=0


#While inside the circle
while (x**2+y**2)**(1./2.)<=r:
    x_step=step*numpy.cos(numpy.random.beta(0.,2.,1./180.)
    y_step=step*numpy.sin(numpy.random.beta(0.,2.,1./180.)
    x+=x_step
    y+=y_step
    step_count+=1

#Print answer
print step_count

要纠正的地方:

  • y_step=step*numpy.sin(numpy.random.beta(0.,2.,1./180.)

SyntaxError: 无效语法

  • ???

【问题讨论】:

  • 您应该首先在您的代码中创建一个圆圈并将您的坐标设置为它的中心
  • 您确实应该在问题中发布一些代码,以便从 StackOverflow 上的程序员那里获得任何帮助。
  • 你根本不需要绕着圈子编程。您所需要的只是一个 x 和 y 坐标,您将不断添加该坐标。对于每一步,计算起始 x、y 位置和您当前位置之间的距离,一旦该距离大于您的圆的半径,您就退出了圆
  • 我很欣赏这些答案。他们让我很好地了解了计算到圆原点的距离的方法,但我仍然不知道如何编写代码来做到这一点。到目前为止,我的代码经验是 if 语句中的 随机数
  • 必须有一些可以编写的代码。用该代码更新您的问题。我们知道这将是错误的,但这就是为什么您在这里寻求有关错误代码的帮助。

标签: python python-2.7 numpy random


【解决方案1】:

我不想让这个帖子无人回答。这是我的最终代码示例:

#Define constants
r=500
step=1
step_count=0

#Defining origin in circle
x=0
y=0

#While inside the circle
while (x**2+y**2)**(1./2.)<=r:
    theta=2*math.pi*random.random()
    x_step=step*math.cos(theta)
    y_step=step*math.sin(theta)
    x+=x_step
    y+=y_step
    step_count+=1

#Print answer
print "It took",step_count,"steps to exit the circle at (",x,",",y,") in (x,y) format)

非常感谢所有回答的人,特别是@quamrana

【讨论】:

    【解决方案2】:

    所以,你快到了。

    这是一个只使用math 的解决方案。 (也是python3)

    import math, random
    
    #Define constants
    r = 500
    step = 1
    
    #define state
    step_count = 0
    
    #Defining origin in circle
    x=0
    y=0
    
    #While inside the circle
    while (x**2 + y**2)**(1./2.) <= r:
        angle = 2 * math.pi * random.random() 
        x_step = step * math.cos(angle)
        y_step = step * math.sin(angle)
        x += x_step
        y += y_step
        step_count += 1
    
    #Print answer
    print(step_count,x,y)
    

    样本输出:

    433126 65.02643317539659 495.86845856661375
    

    注意我是如何计算一次随机角度并用它来计算步长的。

    【讨论】:

      猜你喜欢
      • 2018-02-15
      • 2015-07-04
      • 2019-07-27
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多