【问题标题】:Defining 500 initial random positions of an rotating object in 2-D by Python用 Python 在 2-D 中定义旋转物体的 500 个初始随机位置
【发布时间】:2016-08-15 11:41:10
【问题描述】:

我已经编辑了我的问题。现在我不想在我的函数中使用循环。该函数用于定义二维旋转物体的初始位置。我想得到这样的输出格式:

theta1 theta2 theta3 phi1 phi2 phi3 eta1 eta2 eta3

函数内部对 e 的定义一定是别的东西(我的看法)。谁能帮我得到我想要的输出?

def randposi(N=500):    
    theta = 2*pi* rand()-pi
    phi = arccos(1-2* rand())
    eta = 2*pi*rand()-pi
    r = random.rand(N)
    e = 3*r*array()
    return e

【问题讨论】:

  • 您在寻找性能吗? "good suggestions about how to do this?" - 不完全清楚你的目的。
  • 你一直在使用rand(),它是在哪里定义的? if rand() < 12 这行对我来说没有多大意义(通常随机生成器会生成介于 [0, 1] 之间的数字)
  • 请看我编辑的问题和代码。
  • rand() 是做什么的?特别是当您硬编码 N=500 时,您期望 rand(N)rand(500) 返回什么?
  • 所以你推荐我使用 rand(N=500)?

标签: python numpy rotation 2d


【解决方案1】:

使用随机 numpy 数组怎么样?

类似的东西:

import numpy as np
N=500
#we create a random array 3xN
r = np.random.rand(3,N) 
#tetha is row 0, phi row 1, eta row 2
#we apply the same treatment that is in the question to get the right range
#also note that np.pi is just a predefined float
r[0]=2*np.pi*r[0] -np.pi
r[1]=np.arccos(1-2*r[1]) 
r[2]=2*np.pi*r[2] -np.pi

print(r[0],r[1],r[2])

【讨论】:

  • @Biophysics 我只是指“你的”治疗。抱歉,如果不清楚,我稍微修改了评论。
【解决方案2】:

您可以针对您的情况使用列表推导:

def randpos(N=500):
    # your function code here
    ...

desired = 500
init_positions = [randpos() for i in range(desired)]

【讨论】:

    【解决方案3】:

    所以如果我们让你的函数返回一个元组:

    def randpos():
        theta = 2*pi* rand()-pi
         if rand() < 12:
             if phi < pi:
                phi += pi
             else:
                 phi -= pi
          eta = 2*pi*rand()-pi
          return (theta, phi, eta)
    

    然后调用它 500 次并将结果放入一个元组列表中。

    starting_pos = []
    for x in xrange(500):
        starting_pos.append(randpos)
    

    你有你的解决方案。

    【讨论】:

      【解决方案4】:

      所以,您已经定义了名为 randpos 的函数 f(x),看来该函数不接受任何输入。 N 是您将用于迭代此函数的变量,这里您有几个选项:

      您可以将值存储在一些列表中,如下所示:

      N = 10
      random_positions = [randpos() for i in range(N)]
      print random_positions
      

      如果您不需要存储值,您只需像这样遍历它们:

      for i in range(N):
          print randpos()
      

      如果您愿意,您只需像这样产生您的值:

      def my_iterator(N=500):
          for i in range(N):
              yield randpos()
      
      for rand_pos in my_iterator(N):
          print rand_pos
      

      【讨论】:

        猜你喜欢
        • 2012-10-11
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多