bash bcmath functions
I have two functions for GNU bc in a Bash scrip开发者_JAVA技巧t.
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 interactive bc. bc does not seem to allow multiple functions on one line separated by ; though, so I have to echo -n | bc with newlines at the end of each function. The above output is 2.5, not the expected 3.0 that I get if I type it into bc -i myself. It seems that bash calls bc for each line of echo output, rather than echo'ing it all to a single instance. Is there any workaround for this?
The scale needs to be zero for x%1
to work. You should normally 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 needs a newline after the scale statement:
echo -e "scale=2\n"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc
I believe 1.
is incorrect.
The if()
comparison needs to be X >= 0
.
I find this works
define ceil(x) {
if (x >= 0) { if (x%1>0) return x+(1-(x%1)) else return x }
else return -1*floor(-1*x)
}
define floor(x) {
if (x >= 0) return x-(x%1)
else return -1*ceil(-1*x)
}
精彩评论