#! /bin/zsh # # this file: # https://dataswamp.org/~incal/conf/.zsh/math percent () { local prt=$1 local all=$2 local prc=$(( 100 * ($prt / ($all*1.0)) )) printf "%.1f%%\n" $prc } mph2kmh () { local mph=$1 local sig=$(echo "length($mph)" | bc) units -t --digits $sig "$mph mph" "kilometer/hour" } compact-num () { local num=$1 numfmt \ --format="%.f" \ --round=nearest \ --to=si $num } compare () { local old=$1 local new=$2 printf "%.2f%%\n" $(( 100 * (($new - $old) / ($old*1.0)))) } # https://unix.stackexchange.com/a/13779 numbers () { echo -n "$0 usage: " echo -n "type digit_1 RET digit_2 RET ... digit_n RET\n" echo " then C-d (or ^D) to compute" sort -n | awk ' BEGIN { c = 0; sum = 0; } $1 ~ /^[0-9]*(\.[0-9]*)?$/ { a[c++] = $1; sum += $1; } END { ave = int(sum/c) + 1; if ( (c % 2) == 1 ) { median = a[ int(c/2) ]; } else { median = ( a[c/2] + a[c/2-1] ) / 2; } OFS="\t"; print "items\tsum\tlow\thigh\tmedian\tmean" print c, sum, a[0], a[c-1], median, ave } ' } # what does 'ths' mean? ths () { local value=$1 local denom=${2:-16} local whole=$(( int(floor($value)) )) local rest=$(( $value - $whole )) local frac=$(( int(rint($rest * $denom)) )) if (( $frac > 0 && $(( $frac % 2 )) == 0 )); then local new_denom=$(( denom / 2 )) ths $value $new_denom else local frace (( $frac > 0 )) && frace=-${frac}/${denom} echo ${whole}${frace} fi } # $ ths 2.0 # 2 # $ ths 1.75 # 1-3/4 ths-mm () { local decmal local -i denom num whole if [[ $1 != *.* ]]; then print -- $1 return fi whole=${1%.*} decimal=${1#*.} num=$decimal denom=$(( 10 ** ${#decimal} )) for d in 2 5; do while (( num % d == 0 && denom % d == 0 )); do (( num /= d )) (( denom /= d )) done done (( whole )) && print -n -- $whole (( whole && num )) && print -n ' ' (( num )) && print -n -- $num/$denom print } # minutes 0-59 min2dec () { local minutes=$1 local dec=$(( $minutes / 60.0 )) echo $dec } dec2min () { local dec=$1 local minutes=$(( $dec * 60.0 )) echo $minutes } # base hex2str () { local hex=$1 printf '%b\n' $(sed 's,..,\\x&,g' =(echo $hex)) } change-base () { local from=$1 local to=$2 local value=$3 echo "obase=$to; ibase=$from; $value" | bc } # _16 -> hex2dec () { change-base 16 10 $1 } hex2oct () { change-base 16 8 $1 } hex2bin () { change-base 16 2 $1 } # _10 -> dec2hex () { local dec=$1 local res res=$(change-base 10 16 $dec) echo $res:l } dec2oct () { change-base 10 8 $1 } dec2bin () { change-base 10 2 $1 } # _8 -> oct2hex () { local oct=$1 local res res=$(change-base 8 16 $oct) echo $res:l } oct2dec () { change-base 8 10 $1 } oct2bin () { change-base 8 2 $1 } # _2 -> bin2hex () { local bin=$1 local res res=$(change-base 2 16 $bin) echo $res:l } bin2dec () { change-base 2 10 $1 } bin2oct () { change-base 2 8 $1 } rgb2hex() { local r=$(dec2hex $1) local g=$(dec2hex $2) local b=$(dec2hex $3) echo $r$g$b } pup () { local w=$1 local h=${2:-1.80} local hw=24.99 printf "%+.1f\n" $(( $w - $hw * $h**2 )) }