You are not logged in.
Pages: 1
This bash function
#!/bin/bash
# awk_round
awk_round () {
awk 'BEGIN{printf "%3."'$1'"f\n", "'$2'"}'
}
awk_round "$1" "$2"
seems to work as expected and it is faster than using bc (which also behaves unexpectedly).
awkround 0 42.1
42
awkround 0 42.5
42
awkround 0 42.6
43
awkround 0 -42.6
-43
However one can still use bc in scripts, just perhaps send the floating results to this fancy function (if you need rounding).
Last edited by brontosaurusrex (2017-06-10 22:38:06)
Offline
Nice one...maybe we should have a place where people can contribute some good functions (portably written of course).
Real Men Use Linux
Offline
p.s. speedtest example comparing awk with bc with python
#!/bin/bash
# roundtest
#set -x
#a="-3.6"
#n="0"
awk_round () {
awk 'BEGIN{printf "%3."'$1'"f\n", "'$2'"}'
}
bc_round () {
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
}
py_round () {
echo "print '{0:g}'.format(round($1,$2))" | python
}
# awk = pass
echo "awk"
a=$(awk_round "0" "-3.6")
echo "$a"
time (for ((i=1;i<=100;i++));
do
awk_round "0" "-3.6" > /dev/null
done)
# bc = fail
echo "bc"
b=$(bc_round "-3.6" "0")
echo "$b"
time (for ((i=1;i<=100;i++));
do
bc_round "-3.6" "0" > /dev/null
done)
# python = pass
echo "python"
c=$(py_round "-3.6" "0")
echo "$c"
time (for ((i=1;i<=100;i++));
do
py_round "-3.6" "0" > /dev/null
done)
It would be probably interesting to add python function to this test. Added python func.
Last edited by brontosaurusrex (2017-06-10 23:20:42)
Offline
nobody: Very interesting (over my head), how "portable" is that?
Last edited by brontosaurusrex (2017-06-10 23:29:10)
Offline
Nice one...maybe we should have a place where people can contribute some good functions (portably written of course).
There is - "Scripts, Tutorials and Tips"
Be Excellent to Each Other...
The Bunsenlabs Lithium Desktop » Here
FORUM RULES and posting guidelines «» Help page for forum post formatting
Artwork on DeviantArt «» BunsenLabs on DeviantArt
Offline
DeepDayze wrote:Nice one...maybe we should have a place where people can contribute some good functions (portably written of course).
There is - "Scripts, Tutorials and Tips"
oh my bad
Real Men Use Linux
Offline
Not sure if this is even a correct zsh script, but here: awk vs zsh
#!/usr/bin/zsh
# zsh roundtest
awk_round () {
awk 'BEGIN{printf "%3."'$1'"f\n", "'$2'"}'
}
zsh_round () {
printf %.$1f $(($2))
}
# awk = pass
echo "awk"
a=$(awk_round "0" "-3.6")
echo "$a"
time (for ((i=1;i<=100;i++));
do
awk_round "0" "-3.6" > /dev/null
done)
# zsh = ?
echo "zsh"
z=$(zsh_round "0" "-3.6")
echo "$z"
time (for ((i=1;i<=100;i++));
do
zsh_round "0" "-3.6" > /dev/null
done)
Actuall perhaps this should be bash script as well (the one that calls zsh).
@nobody: ctypes vs zsh?
Last edited by brontosaurusrex (2017-06-12 11:18:39)
Offline
Pages: 1