How to compare two floats?
tito
farmatito at tiscali.it
Sat May 23 22:20:54 UTC 2015
On Saturday 23 May 2015 21:41:51 bifferos wrote:
> I'm trying to write a thermostat using busybox shell, however the only way I
> could think to compare two float temperatures (without adding awk) was to
> multiply them up in dc and then compare as integers. In the end I modified
> dc to add a comparison operator, which probably breaks the spirit of dc
> somewhat. I'm interested if I missed a trick somewhere. Is there another
> way to do this? Is this considered a heinous thing to do to dc?
>
> Thanks,Biff.
> --- a/miscutils/dc.c
> +++ b/miscutils/dc.c
> @@ -103,6 +103,18 @@ static void divide(void)
> push(pop() / divisor);
> }
>
> +static void gt(void)
> +{
> + double rhs = pop();
> + push((pop() > rhs) ? 1 : 0);
> +}
> +
> +static void ge(void)
> +{
> + double rhs = pop();
> + push((pop() >= rhs) ? 1 : 0);
> +}
> +
> static void mod(void)
> {
> data_t d = pop();
> @@ -204,6 +216,8 @@ static const struct op operators[] = {
> {"mul", mul},
> {"/", divide},
> {"div", divide},
> + {"gt", gt},
> + {"ge", ge},
> #if ENABLE_FEATURE_DC_LIBM
> {"**", power},
> {"exp", power},
Hi,
is the number of decimal digits fixed? If yes
something like this could work:
debian:~$ SEP='.'
debian:~$ T1=`echo 19.2 | tr -d '$SEP'`
debian:~$ echo $T1
192
debian:~$ T2=`echo 20.0 | tr -d '$SEP'`
debian:~$ echo $T2
200
debian:~$ if [ $T1 -le $T2 ] ; then echo $T2; else echo $T1; fi
200
if the number of decimal digits is not fixed it is a little more
complicated as they need to be padded (with printf ?).
Just my 0.2 cents.
Ciao,
Tito
More information about the busybox
mailing list