通过 Python 在 2-D 中定义旋转物体的 500 个初始随机位置
Defining 500 initial random positions of an rotating object in 2-D by Python
我已经编辑了我的问题。现在我不想在我的函数中使用循环。该函数用于定义二维旋转对象的初始位置。我想得到这样的输出格式:
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
所以如果我们让你的函数 return 成为一个元组:
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)
你有你的解决方案。
对于你的情况,你可以使用列表推导式:
def randpos(N=500):
# your function code here
...
desired = 500
init_positions = [randpos() for i in range(desired)]
所以,你已经定义了你的函数 f(x) 叫做 randpos,看起来这个函数不接受任何输入。 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
使用随机 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])
我已经编辑了我的问题。现在我不想在我的函数中使用循环。该函数用于定义二维旋转对象的初始位置。我想得到这样的输出格式:
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
所以如果我们让你的函数 return 成为一个元组:
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)
你有你的解决方案。
对于你的情况,你可以使用列表推导式:
def randpos(N=500):
# your function code here
...
desired = 500
init_positions = [randpos() for i in range(desired)]
所以,你已经定义了你的函数 f(x) 叫做 randpos,看起来这个函数不接受任何输入。 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
使用随机 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])