Bash bcmath functions
I have two functions for GNU bc in a Bash script.
BC_CEIL="define ceil(x) { if (x>0) { if (x%1>0) return x+(1-(x%1)) else return x } else return -1*floor(-1*x) }\n"
BC_FLOOR="define floor(x) { if (x>0) return x-(x%1) else return -1*ceil(-1*x) }\n"
echo -e "scale=2"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc
Both functions work fine in bc interactive mode. bc doesn't seem to allow multiple functions on the same line, separated; though, so I need echo -n | bc with newlines at the end of each function. The above output is 2.5 and not the expected 3.0 which I get if I type it into bc-i. It looks like Bash is calling bc for each line of echo-out, rather than echoing just one instance. Is there a workaround for this?
+2
a source to share
2 answers
The scale must be zero for x%1
. Usually, you should only have one return from a function.
define ceil(x) { auto savescale; savescale = scale; scale = 0; if (x>0) { if (x%1>0) result = x+(1-(x%1)) else result = x } else result = -1*floor(-1*x); scale = savescale; return result }
define floor(x) { auto savescale; savescale = scale; scale = 0; if (x>0) result = x-(x%1) else result = -1*ceil(-1*x); scale = savescale; return result }
This scale requires a newline:
echo -e "scale=2\n"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc
+2
a source to share