0


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

Jay
  • 23
  • 4
  • 1
    What is the problem you are having with your script? This is not a math problem solving service. – Mithrandir Oct 09 '15 at 07:42
  • Value1=3947 Value2=5853, I am calculating variance percentage using echo "$Value1" "$Value2" | awk '{print ($1-$2)/$1*100}', I like to know its right approach or not..? If its right approach then could you please help me how to get abs value. – Jay Oct 09 '15 at 07:45
  • And see [this question](http://stackoverflow.com/questions/11184915/absolute-value-in-awk-doesnt-work) and related answer for the abs function not present in awk – Dfaure Oct 09 '15 at 08:04

1 Answers1

1

Pseudo floating point using pure

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%

Pseudo abs() for using wrong negative values

percent() {
    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!

F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137