Files
bash_utils/math.sh
2024-03-22 07:02:10 +01:00

74 lines
1.6 KiB
Bash

#!/bin/bash
DIRECTORY=$(cd `dirname $0` && pwd)
. /home/spezi/Scripts/utils/utils.sh
# https://unix.stackexchange.com/questions/66766/float-operation-with-bc
# https://unix.stackexchange.com/questions/89712/how-to-convert-floating-point-number-to-integer
# xargs: https://stackoverflow.com/questions/19148370/piping-seq-to-printf-for-number-formatting
divideint () {
bc <<< "scale=$scale; $1/$2" | xargs printf "%.0f\n"
}
multiint () {
bc <<< "scale=2; $1*$2" | xargs printf "%.0f\n"
}
divide () {
if [ -z $3 ]; then
scale=2
else
scale=$3
fi
bc <<< "scale=$scale; $1/$2"
}
multiply () {
if [ -z $3 ]; then
scale=2
else
scale=$3
fi
bc <<< "scale=$scale; $1*$2"
}
avgoftwo () {
sum=$(bc <<< "$1+$2")
divideint $sum 2
}
max () {
declare -a allnumbers
for arg in "$@"; do
if isarray $arg; then
for elem in ${arg[@]}; do
[[ $elem -eq $elem ]] && allnumbers+=($elem)
done
else
[[ $arg -eq $arg ]] && allnumbers+=($arg)
fi
done
max=${allnumbers[0]}
for n in "${allnumbers[@]}"; do
((n > max)) && max=$n
done
echo $max
}
min () {
declare -a allnumbers
for arg in "$@"; do
if isarray $arg; then
for elem in ${arg[@]}; do
[[ $elem -eq $elem ]] && allnumbers+=($elem)
done
else
[[ $arg -eq $arg ]] && allnumbers+=($arg)
fi
done
min=${allnumbers[0]}
for n in "${allnumbers[@]}"; do
((n < min)) && min=$n
done
echo $min
}