mirror of
https://dicksdeathabove.xyz/~mia/psh-fractional
synced 2024-11-09 16:44:41 +00:00
58 lines
1.5 KiB
Bash
Executable file
58 lines
1.5 KiB
Bash
Executable file
#!/bin/sh
|
|
rad(){ # add decimal to $1 based on $2
|
|
# literal reverse of what ad() from multiplication/mul does
|
|
m="$1"; n=0; while [ "$m" ]; do
|
|
next="${m#?}"
|
|
[ "$n" -eq "$2" ] && break
|
|
e="${e}${m%$next}"
|
|
m="$next"; : $((n+=1))
|
|
done
|
|
w="${1#$e}"; echo "${3}${e}.${w:-0}"
|
|
}
|
|
fd() {
|
|
m="$1"; n=1; while [ "$m" ]; do
|
|
next="${m%?}"
|
|
[ "$n" -eq "${#1}" ] && {
|
|
echo "${m%next}"
|
|
break
|
|
}
|
|
: $((n+=1)); m="$next"
|
|
done
|
|
}
|
|
[ -z "${1##*.*}" -o -z "${2##*.*}" ] || { # if not floats
|
|
echo "$(($1-$2))"
|
|
exit 0
|
|
}
|
|
if [ ! -z "${1##*.*}" ]; then
|
|
set -- "${1}.0" "$2"; d="${1#*.}"; d2="${2#*.}"
|
|
until [ "${#d}" -eq "${#d2}" ]; do
|
|
set -- "${1}0" "$2"
|
|
d="${1#*.}"
|
|
done
|
|
elif [ ! -z "${2##*.*}" ]; then
|
|
set -- "$1" "${2}.0"; d="${2#*.}"; d2="${1#*.}"
|
|
until [ "${#d}" -eq "${#d2}" ]; do
|
|
set -- "$1" "${2}0"
|
|
d="${2#*.}"
|
|
done
|
|
fi # if $1/$2 is not a float; convert to float
|
|
m1="${1%.*}${1#*.}"; m2="${2%.*}${2#*.}"
|
|
dn=$((${1%.*}-${2%.*})); dn="${dn#-}"; dn="${#dn}"
|
|
# decimal place is determined by the length of $1-$2
|
|
# without decimals
|
|
## SWAP IF $1 > $2; negative handling
|
|
[ "$m1" -lt "$m2" ] && {
|
|
set -- "$2" "$1"
|
|
m1="${1%.*}${1#*.}"; m2="${2%.*}${2#*.}"; nr="-"
|
|
}
|
|
#echo "$m1 $m2 $dn"
|
|
until [ "${m1#0}" = "$m1" ]; do
|
|
m1="${m1#0}"
|
|
done
|
|
until [ "${m2#0}" = "$m2" ]; do
|
|
m2="${m2#0}"
|
|
done # dash has issues when numbers have leading 0's
|
|
# zsh,bash,etc don't need this at all
|
|
# and really dash shouldn't either but /shrug
|
|
rad "$((m1-m2))" "$dn" "${nr}"
|