随机化盒子内的(x,y,z)坐标

2024-09-29 00:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python相当陌生,在我当前的作业中,它研究了3D中的粒子

问题的第一部分要求创建一个程序,将相同的、不重叠的粒子放入立方晶格中。所以我下面的代码只是遍历所有可能的组合,将其放入一个XYZ文件中。在

xyz文件的格式如下:

1000.000000
comment goes here
H 0.000000 0.000000 0.000000
H 0.000000 0.000000 1.000000
H 0.000000 0.000000 2.000000
H 0.000000 0.000000 3.000000
H 0.000000 0.000000 4.000000
H 0.000000 0.000000 5.000000
H 0.000000 0.000000 6.000000
H 0.000000 0.000000 7.000000
H 0.000000 0.000000 8.000000

下一部分我要做的是同样的事情,但是把它们随机地放在一起,限制粒子的数量。这是我第一部分的代码。在

^{pr2}$

我感到困惑的是我应该如何随机化我的粒子/坐标并确保没有重叠。在

有什么想法吗?提前谢谢!在

**编辑:这是我目前为止所遇到的问题,除了要求改变L并尽量减少运行程序所需的时间外-不确定是什么

import random
import time

start_time=time.time() 

text_file=open("textfile.xyz","w")
text_file.write("512\n")
text_file.write("Comment goes here\n")

L=12.5
d=1

#place particles
for partciles in range(0,512)
    proxcheck=1
    while proxcheck !=2 #when the particles has been placed, proxcheck will be set=2, and the program will move onto next
    x,y,z=random.random()*L,random.random()*L,random.random()*L #random numbers for positions
    skipfirsttwolines,proxcheck=0,1;

For line in text_file
    skipfirsttwolines=skipfirsttwolines+1;
    if skipfirsttwolines>2: #in xyz file we dont look at first two lines
        proxcheck=0 #if no overlap particle will be placed
        oldvals=line.split(none)
        oldx=float(oldvals[1])
        oldy=float(oldvals[2])
        oldz=float(oldvals[3])

不知道从这里到哪里,或者我是否应该采取这种方法来确保没有重叠

@大卫:

我就是这么想的,有什么建议吗?在

x,y,z=[],[],[]
for j in range(0,512):
    x.append(0)
    y.append(0)
    z.append(0)
xyz_line = '\n{0} {1} {2} {3}'.format('O',x[0],y[0],z[0])
f.write(xyz_line)

Tags: textinfortimeline粒子randomfloat
1条回答
网友
1楼 · 发布于 2024-09-29 00:15:38

你可以用代码创建一个随机点

import random

p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))

但是,如果您需要防止在同一个位置有两个,您可以(在将num_points设置为所需点数之后):

^{pr2}$

要将结果点写入文件,请执行以下操作:

for p in points:
    f.write("%s %s %s\n" % p)

相关问题 更多 >