You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

粒子生成器运行卡顿求助及粒子平均距离计算咨询

粒子生成器问题排查与平均距离实现

一、程序卡住的问题修正

你的代码存在几个关键错误,导致程序无法正常运行:

1. 变量名与循环条件错误

  • gen_part函数参数为density,但内部计算particle_count时误用了全局变量density_input,应改为使用函数参数density。
  • while循环条件写反:原本的while particle_count < len(particles_arr)会导致初始时数组为空(长度0),条件不成立,循环直接跳过;正确条件应为while len(particles_arr) < particle_count,直到生成足够数量的粒子。

2. 代码缩进与语法错误

你代码中的(edit:)和对应的)是多余的,且后续的重叠判断代码缩进错误,应包含在while循环内部。

3. 重叠判断逻辑问题

  • 每次判断重叠时重复创建Particle对象,效率低下,可提前创建临时粒子。
  • 重叠时的概率逻辑有误:当检测到与已有粒子重叠时,若随机概率未通过则标记为重叠,否则允许添加;原代码的continue仅跳过当前粒子的判断,无法正确处理重叠逻辑。

修正后的完整代码

import random
import math
import matplotlib.pyplot as plt

class Particle:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius
        
    def overlap(self, other):
        distance = math.hypot(self.x - other.x, self.y - other.y)
        return distance < (self.radius + other.radius)  # 修正:重叠判断应为两半径之和

def gen_part(density, box_size, radius, inclusion_prob):
    particles_arr = []
    particle_count = int((box_size ** 2) * density)  # 转为整数,避免小数数量
    
    while len(particles_arr) < particle_count:
        x = random.random() * box_size
        y = random.random() * box_size
        new_particle = Particle(x, y, radius)
        overlap = False
        
        for trail_particle in particles_arr:
            if new_particle.overlap(trail_particle):
                # 重叠时,若概率不通过则标记为重叠
                if random.random() >= inclusion_prob:
                    overlap = True
                    break
        
        if not overlap:
            particles_arr.append(new_particle)
        else:
            # 重叠但概率通过时添加粒子
            if random.random() < inclusion_prob:
                particles_arr.append(new_particle)
    return particles_arr

radius = float(input("Enter particle radius: "))
box_size = float(input("Enter box width: "))
inclusion_prob = float(input("Enter inclusion probability (between 0 and 1): "))
density_input = float(input('enter density'))

partis = gen_part(density_input, box_size, radius, inclusion_prob)

fig, ax = plt.subplots(figsize=(6, 6))
ax.set_facecolor('black')  # 设置背景色,让白色粒子更明显
for particle in partis:
    circle = plt.Circle((particle.x, particle.y), particle.radius, color='white')
    ax.add_artist(circle)

ax.set_xlim([0, box_size])
ax.set_ylim([0, box_size])
ax.set_xticks([])
ax.set_yticks([])
plt.show()

二、平均距离计算功能实现

要计算所有粒子间的平均距离,需遍历每一对不重复的粒子,累加距离后除以总对数:

实现代码

在生成partis数组后,添加以下代码:

def calculate_average_distance(particles):
    total_distance = 0.0
    num_particles = len(particles)
    if num_particles < 2:
        return 0.0  # 粒子数不足时返回0
    
    pair_count = 0
    for i in range(num_particles):
        for j in range(i + 1, num_particles):
            p1 = particles[i]
            p2 = particles[j]
            distance = math.hypot(p1.x - p2.x, p1.y - p2.y)
            total_distance += distance
            pair_count += 1
    
    return total_distance / pair_count

average_dist = calculate_average_distance(partis)
print(f"所有粒子间的平均距离: {average_dist:.4f}")

说明

  • 使用math.hypot计算两点距离,比手动开平方更简洁高效。
  • 双重循环中j从i+1开始,避免重复计算同一对粒子(如粒子A和B与B和A视为同一对)。
  • 粒子数小于2时直接返回0,避免除以0错误。

内容的提问来源于stack exchange,提问作者user3146888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:32:56