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

如何统计2D Gaussian分布中不同半径圆周内的粒子数量

实现2D高斯分布内随半径变化的元素数量统计

没问题呀,刚学Python遇到这类问题太正常了~我来帮你一步步实现这个需求,同时保留你原来的可视化代码:

核心思路

要实现这个功能,我们需要:

  1. 将两个一维高斯数组组合成2D坐标点
  2. 计算每个点到2D高斯分布中心的距离
  3. 生成一系列连续的半径值(从大到小或从小到大)
  4. 统计每个半径范围内的点数量
  5. 绘制半径与点数量的关系图

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# 生成两个一维高斯分布
mu1, sigma1 = 0, 0.1 # x轴均值和标准差
s1 = np.random.normal(mu1, sigma1, 10000)
mu2, sigma2 = 0.8, 0.3 # y轴均值和标准差
s2 = np.random.normal(mu2, sigma2, 10000)

# --- 原有可视化部分保留 ---
# 两个一维高斯的直方图
plt.figure(1)
plt.title('Histogram of Two 1D Gaussian Distributions')
plt.hist(s1, 100, alpha=0.5, label='s1 (μ=0, σ=0.1)')
plt.hist(s2, 100, alpha=0.5, label='s2 (μ=0.8, σ=0.3)')
plt.legend()
plt.show()

# 2D高斯分布的直方图
plt.figure(2)
plt.title('2D-Gaussian Distribution')
bins = plt.hist2d(s1, s2, 100)
cb = plt.colorbar()
cb.set_label('counts in bin')
plt.xlabel('s1 values')
plt.ylabel('s2 values')
plt.show()

# --- 新增:半径与点数量的统计与可视化 ---
# 1. 组合成2D坐标点
points = np.column_stack((s1, s2))
# 2. 计算每个点到2D高斯中心(mu1, mu2)的距离
distances = np.sqrt((s1 - mu1)**2 + (s2 - mu2)**2)
# 3. 生成一系列半径值(从0到最大距离,这里取2足够覆盖所有点)
radii = np.linspace(0, 2, 100) # 生成100个从0到2的半径点,可按需调整数量
# 4. 统计每个半径内的点数量
counts = []
for r in radii:
    count = np.sum(distances <= r)
    counts.append(count)

# 5. 绘制半径与点数量的关系图
plt.figure(3)
plt.title('Number of Points Within Radius (2D Gaussian)')
plt.plot(radii, counts, color='darkorange', linewidth=2)
plt.xlabel('Radius from center (μ1, μ2)')
plt.ylabel('Number of points in circle')
plt.grid(alpha=0.3)
plt.show()

代码细节说明

  • 组合2D点:用np.column_stack把s1和s2合并成N×2的坐标数组,方便后续距离计算
  • 计算距离:使用欧氏距离公式,这里选择2D高斯的真实中心(mu1, mu2)作为圆心;如果想以原点为圆心,把公式里的mu1和mu2换成0即可
  • 生成半径序列:np.linspace生成均匀分布的半径值,你可以调整第二个参数(最大半径)或者第三个参数(半径数量)来优化曲线的平滑度
  • 统计数量:用np.sum(distances <= r)快速统计满足条件的点数量,比循环遍历每个点更高效
  • 比例展示(可选):如果想展示占总点数的比例,只需把counts.append(count)改成counts.append(count / len(s1)),同时把y轴标签改成Proportion of points in circle

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:07:42