|
参考教材《概率论与数理统计》第四版, 高等教育出版社 盛骤等编 P132
根据书中定义求得的结果与根据MATLAB的quantile和prctile得到的结果有一些差别,原因是计算方法不同。我编写如下MATLAB程序进行对比,找找其中的差别吧?
维基百科: https://en.wikipedia.org/wiki/Quantile 提供了9个公式。
clear,clc
x = [122,126,133,140,145,145,149,150,157,...
162,166,175,177,177,183,188,199,212];
xs = sort(x); p = [0.1,0.25,0.5,0.75 0.975];
% 分位数
n = length(x); np = floor(n*p); r = n*p-np;
id = (r ==0); xnp(id) = (xs(np(id))+xs(np(id)+1))/2;
idn = (r~=0); xnp(idn) = xs(np(idn)+1);
xnp
%%% 下面用了循环,和不用循环结果相同,只是更易理解
for i = 1:length(p)
if n*p(i)==np(i)
xnp(i) = (xs(np(i))+xs(np(i)+1))/2;
else
xnp(i) = xs(np(i)+1);
end
end
xnp
%plot
%%% MATLAB自带的命令,有细微差别, 感觉自带的比较合理
r = p*n;
k = floor(r+0.5); % K gives the index for the row just before r
kp1 = k + 1; % K+1 gives the index for the row just after r
r = r - k; % R is the ratio between the K and K+1 rows
k(k==0)=1; kp1(kp1==n+1)=n;
ynp = (0.5-r).*xs(k)+(0.5+r).*xs(kp1)
%%% 内嵌函数 quantile 和 prctile
yp = quantile(x,p)
yp = prctile(x,p*100)
运行结果
xnp =
126.0000 145.0000 159.5000 177.0000 212.0000
xnp =
126.0000 145.0000 159.5000 177.0000 212.0000
ynp =
128.1000 145.0000 159.5000 177.0000 212.0000
yp =
128.1000 145.0000 159.5000 177.0000 212.0000
yp =
128.1000 145.0000 159.5000 177.0000 212.0000
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2025-1-6 14:08
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社