Advertisement
devinteske

Floating Point Precision in Bourne Shell

Nov 26th, 2014
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.65 KB | None | 0 0
  1. #!/bin/sh
  2. # f_perc [-n precision] dividend [/] divisor [var_to_set]
  3. #
  4. # Calculate floating-point percentage for dividend within divisor. Default is
  5. # to provide two significant figures (floating-point digits) unless given
  6. # `-n precision' where precision is the number of desired sig-figs. An optional
  7. # division-sign [/] may appear between the dividend and divisor.
  8. #
  9. # If var_to_set is missing or NULL, the result is printed to standard output.
  10. # NB: This function does not round-up the last sig-fig (regardless).
  11. #
  12. f_perc()
  13. {
  14.         local OPTIND=1 OPTARG __flag __np=2
  15.         while getopts n: __flag; do
  16.                 case "$__flag" in n) __np="$OPTARG" ;; esac
  17.         done
  18.         shift $(( $OPTIND - 1 ))
  19.         local __dividend="$1" __divisor="$2" __var_to_set="$3"
  20.         [ "$__divisor" = "/" ] && __divisor="$3" __var_to_set="$4"
  21.         local __whole=0 __remainder=$(( $__dividend * 100 )) __n=1
  22.         local __answer=$(( $__remainder / $__divisor ))
  23.         [ $__np -gt 0 ] && __answer=$__answer.
  24.         while [ $__n -le $__np ]; do
  25.                 __whole=$(( $__remainder / $__divisor ))
  26.                 __remainder=$(( $__remainder % $__divisor * 10 ))
  27.                 __answer=$__answer$(( $__remainder / $__divisor ))
  28.                 __n=$(( $__n + 1 ))
  29.         done
  30.         if [ "$__var_to_set" ]; then
  31.                 setvar "$__var_to_set" "$__answer%"
  32.         else
  33.                 echo $__answer%
  34.         fi
  35. }
  36. run=0 start=$( date +%s )
  37. while [ $run -lt 100000 ]; do
  38.         f_perc -n5 1 / 85 perc # 1.17647%
  39.         run=$(( $run + 1 ))
  40. done
  41. stop=$( date +%s )
  42. echo "$run runs in ~$(( $stop - $start ))s; perc=[$perc]"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement