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).
Thanks
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).
Thanks
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
This could be used this way:
percent 10 50
20.00%
or to set a variable:
percent 10 50 result
echo $result
20.00%
abs()
for using wrong negative valuespercent() {
local p=000$((${1#-}00000/$2));
printf ${3+-v} $3 "%.2f%%" ${p:0:${#p}-3}.${p:${#p}-3};
}
This will drop any minux sign in your 1st argument:
value1=3947
value2=5853
percent $((value1-value2)) $value1 result
echo $result
48.29%
Or with more precision:
percent() {
local p;
printf -v p 00000%u $((${1#-}0000000/$2));
printf ${3+-v} $3 "%.4f%%" ${p:0:${#p}-5}.${p:${#p}-5};
}
Could compute:
value1=3947
value2=5853
percent $((value1-value2)) $value1 result
echo $result
48.2898%
Of course, as this use bash's 64bits integers, this will only work with small values: 1st argument could not be bigger than 922337203685
!