用于方差百分比计算的Shell脚本 [英] Shell script for variance percentage calculation
本文介绍了用于方差百分比计算的Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要计算2个数字之间的方差百分比差异,这可以帮助我在Unix Shell脚本中进行的工作.另外,我喜欢将输出作为abs值(总是+ ve).
I need to calculate variance percentage difference between 2 numbers could some one help me how i can do in unix shell scripting. Also the I like to have the output as abs value (always +ve).
谢谢
推荐答案
使用 pure bash
几年前,我写了这篇文章:
Pseudo floating point using pure bash
I wrote this some years ago:
#
# Bash source file for percent computing
#
# (C) 2011-2012 Felix Hauri - felix@f-hauri.ch
# Licensed under terms of LGPL v3. www.gnu.org
# after sourcing script:
# syntaxe: percent <amount> <total> [varname]
percent() {
local p=000$((${1}00000/$2))
printf ${3+-v} $3 "%.2f%%" ${p:0:${#p}-3}.${p:${#p}-3}
}
export -f percent
可以这样使用:
percent 10 50
20.00%
或设置一个变量:
percent 10 50 result
echo $result
20.00%
伪 abs()
使用错误的负值
percent() {
local p=000$((${1#-}00000/$2));
printf ${3+-v} $3 "%.2f%%" ${p:0:${#p}-3}.${p:${#p}-3};
}
这会在您的第一个参数中删除所有minux符号:
This will drop any minux sign in your 1st argument:
value1=3947
value2=5853
percent $((value1-value2)) $value1 result
echo $result
48.29%
或更精确地说:
percent() {
local p;
printf -v p 00000%u $((${1#-}0000000/$2));
printf ${3+-v} $3 "%.4f%%" ${p:0:${#p}-5}.${p:${#p}-5};
}
可以计算:
value1=3947
value2=5853
percent $((value1-value2)) $value1 result
echo $result
48.2898%
当然,由于它使用bash的64位整数,因此仅适用于较小的值:第一个参数不能大于 922337203685
!
Of course, as this use bash's 64bits integers, this will only work with small values: 1st argument could not be bigger than 922337203685
!
这篇关于用于方差百分比计算的Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文