计算基于5个值的百分位数,需要创建一个将百分位数映射到它们之间插值的过程。这个过程称为“分段线性函数”(也称为pwlf
)。
F(100) = 34.5
F(75) = 33.7
F(50) = 32.2
F(25) = 31.8
F(0) = 30.4
对于范围在0..100内的任何其他x的映射,需要在线性插值F(L)和F(H)之间 - 其中L是最接近x的最高值,并且H=L+1。
awk '
#! /bin/env awk
# PWLF Interpolation function, take a value, and two arrays for X & Y
function pwlf(x, px, py) {
# Shortcut to calculate low index of X, >= p
p_l = 1+int(x/25)
p_h = p_l+1
x_l = px[p_l]
x_h = px[p_h]
y_l = py[p_l]
y_h = py[p_h]
#print "X=", x, p_l, p_h, x_l, x_h, y_l, y_h
return y_l+(y_h-y_l)*(x-x_l)/(x_h-x_l)
}
# Read f Input in yy array, setup xx
{ yy[n*25] = $1 ; n++ }
# Print the table
END {
# Sort values of yy
ny = asort(yy) ;
# Create xx array 0, 25, ..., 100
for (i=1 ; i<=ny ; i++) xx[i]=25*(i-1)
# Prepare list of requested results
ns = split("99 97 95 90 80 70 60 50 40 30 20 10 5", pv)
for (i=1 ; i<=ns ; i++) printf "%dth %.1f\n", pv[i], pwlf(pv[i], xx, yy) ;
}
' input
从OP的评论看来,最好将整个脚本放到script.awk中,并作为一行执行。 解决方案具有“#!”来调用awk脚本。 实际上是一个bash脚本。
/path/to/script.awk < input