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

如何使用Python或R拟合半正态分布并计算其三倍标准差

Python 解决方案

调用scipy.stats.halfnorm的fit方法可直接对样本数据做半正态分布拟合,半正态分布的尺度参数scale即为分布的标准差,直接乘3即可得到目标值:

import pandas as pd
import numpy as np
from scipy.stats import halfnorm
import matplotlib.pyplot as plt

# 原始数据
df = pd.DataFrame([100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 5, 1, 0.9, 0.07, 0.001, 0.00001], columns=['Frequency'])
data = df['Frequency'].values

# 拟合半正态分布,返回值分别为位置参数loc、尺度参数scale(即半正态分布的标准差)
# 如果业务场景默认半正态的位置参数为0,可添加floc=0参数固定loc,拟合结果更贴合预期:halfnorm.fit(data, floc=0)
loc, scale = halfnorm.fit(data)
# 计算三倍标准差
three_sigma = 3 * scale

print(f"拟合得到半正态分布标准差:{scale:.4f}")
print(f"三倍标准差:{three_sigma:.4f}")

# 可选:拟合效果可视化验证
plt.hist(data, density=True, alpha=0.6, label='样本分布')
x = np.linspace(min(data), max(data), 1000)
plt.plot(x, halfnorm.pdf(x, loc=loc, scale=scale), 'r', label='拟合半正态分布')
plt.legend()
plt.show()
R 解决方案

使用fitdistrplus包即可完成半正态分布拟合,代码如下:

# 首次使用先安装依赖包
install.packages("fitdistrplus")
library(fitdistrplus)

# 构造原始数据
data <- c(100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 5, 1, 0.9, 0.07, 0.001, 0.00001)

# 拟合半正态分布
fit <- fitdist(data, "halfnorm")
# 提取分布标准差
sd <- fit$estimate["sd"]
# 计算三倍标准差
three_sigma = 3 * sd

cat(paste0("拟合得到半正态分布标准差:", round(sd,4), "\n"))
cat(paste0("三倍标准差:", round(three_sigma,4), "\n"))

# 可选:拟合效果可视化
plot(fit)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:45:01