Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/sh
- # f_perc [-n precision] dividend [/] divisor [var_to_set]
- #
- # Calculate floating-point percentage for dividend within divisor. Default is
- # to provide two significant figures (floating-point digits) unless given
- # `-n precision' where precision is the number of desired sig-figs. An optional
- # division-sign [/] may appear between the dividend and divisor.
- #
- # If var_to_set is missing or NULL, the result is printed to standard output.
- # NB: This function does not round-up the last sig-fig (regardless).
- #
- f_perc()
- {
- local OPTIND=1 OPTARG __flag __np=2
- while getopts n: __flag; do
- case "$__flag" in n) __np="$OPTARG" ;; esac
- done
- shift $(( $OPTIND - 1 ))
- local __dividend="$1" __divisor="$2" __var_to_set="$3"
- [ "$__divisor" = "/" ] && __divisor="$3" __var_to_set="$4"
- local __whole=0 __remainder=$(( $__dividend * 100 )) __n=1
- local __answer=$(( $__remainder / $__divisor ))
- [ $__np -gt 0 ] && __answer=$__answer.
- while [ $__n -le $__np ]; do
- __whole=$(( $__remainder / $__divisor ))
- __remainder=$(( $__remainder % $__divisor * 10 ))
- __answer=$__answer$(( $__remainder / $__divisor ))
- __n=$(( $__n + 1 ))
- done
- if [ "$__var_to_set" ]; then
- setvar "$__var_to_set" "$__answer%"
- else
- echo $__answer%
- fi
- }
- run=0 start=$( date +%s )
- while [ $run -lt 100000 ]; do
- f_perc -n5 1 / 85 perc # 1.17647%
- run=$(( $run + 1 ))
- done
- stop=$( date +%s )
- echo "$run runs in ~$(( $stop - $start ))s; perc=[$perc]"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement