import math
import random
#判断两个小球是否相离,如果相离返回true,如果相交或者内切返回false
def isIntersectOrIncircle(ball1,ball2,d):
distance=math.sqrt((ball1['x']-ball2['x'])*(ball1['x']-ball2['x'])+(ball1['y']-ball2['y'])*(ball1['y']-ball2['y'])+(ball1['z']-ball2['z'])*(ball1['z']-ball2['z']))
if distance > (2*math.sqrt(3)*d+math.sqrt(3)*(ball1['r']+ball2['r'])):
return True
else:
return False
#主程序
if __name__=='__main__':
cylinder_radius=0.025
cylinder_height=0.025
ball_radius_min=0.0005
ball_radius_max=0.002
plot_ratio_min=0.1
plot_ratio_max=0.1001
d=0.0002
filename = 'C:\\Users\\gsr\\Desktop\\test_data2.txt'
ball_volume=0.0
cylinder_volume=cylinder_radius*cylinder_radius*cylinder_height
plot_ratio=ball_volume/cylinder_volume
ball_list=[]
while plot_ratio<plot_ratio_min:
flag = True
# 随机生成小球半径
r = random.random() * (ball_radius_max - ball_radius_min) + ball_radius_min
# 随机生成极坐标长度
l = random.random() * (cylinder_radius - math.sqrt(2) * (r + d) - 0.001)
# 随机生成极坐标角度
angle = random.random() * (2 * math.pi)
# 根据极坐标求球心的x,y坐标
x = l * math.cos(angle)
y = l * math.sin(angle)
# 随机生成球的z坐标
z = random.random() * (cylinder_height - 2 * (r + d + 0.001)) + (r + d + 0.001)
ball1={'x':x,'y':y,'z':z,'r':r}
if len(ball_list)>0:
for item in ball_list:
if not isIntersectOrIncircle(ball1,item,d):
flag=False
break
if flag:
volume=4/3*math.pi*r*r*r
if (ball_volume + volume)/cylinder_volume<plot_ratio_max:
ball_list.append(ball1)
ball_volume = ball_volume + volume
plot_ratio=ball_volume/cylinder_volume
with open(filename, 'w') as f:
for item in ball_list:
f.write(str(item['r'])+','+str(item['x'])+','+str(item['y'])+','+str(item['z'])+'\n')
print(len(ball_list))